Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dart - Flutter video_player dispose

I'm using provider with video_player to manage the state.

VideoProvider has:

videoPlayerController = VideoPlayerController.network(...);

which I frequently change when the user switches to a new video (same screen). If I directly assign a new VideoPlayerController.network(...) into the videoPlayerController, the old video will still play and you can hear the sound. The workaround is to videoPlayerController.pause() then assign a new VideoPlayerCOntroller.network afterwards.

Is the previous Video being disposed by GC? Are there any performance issues with this? I want to get rid of the previous video and the resources used before switching to a new one. I can't videoPlayerController.dispose() before switching because it causes an error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you call dispose your controller is still being used by VideoPlayer widget. First, you need to make sure that it's not used anymore (setting controller in state to null) and AFTER that you call dispose.

I'm not sure about your state management via Provider, but I'll give you an example how to do this with regular State.

  VideoPlayerController _controller;

  void _initController(String link) {
    _controller = VideoPlayerController.network(link)
      ..initialize().then((_) {
        setState(() {});
      });
  }

  Future<void> _onControllerChange(String link) async {
    if (_controller == null) {
      // If there was no controller, just create a new one
      _initController(link);
    } else {
      // If there was a controller, we need to dispose of the old one first
      final oldController = _controller;

      // Registering a callback for the end of next frame
      // to dispose of an old controller
      // (which won't be used anymore after calling setState)
      WidgetsBinding.instance.addPostFrameCallback((_) async {
        await oldController.dispose();

        // Initing new controller
        _initController(link);
      });

      // Making sure that controller is not used by setting it to null
      setState(() {
        _controller = null;
      });
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...