Home > Software engineering >  Flutter dispose() if controller have been initialized (Video Player)
Flutter dispose() if controller have been initialized (Video Player)

Time:04-29

My App is disposing a controller everytime I leave the page, however, I am not initializing the controller with initState() and am initializing it onTap, so I was wondering if it is possible to check if the controller has been initialized to figure out if it should dispose it or not.

The Controller is:

VideoPlayerController _controller;

And I am initializing it after an onTap:

onTap: () {
 setState(() {
     _initVideo(file);
 });
}

_initVideo(Future<File> videoFile) async {
    final video = await videoFile;
    _controller = VideoPlayerController.file(video)

      ..setLooping(false)
      ..initialize().then((value) => setState(() {
            _controller.addListener(() {
              setState(() {
              });
            });
          }));
  }

And for the dispose I am trying to check whether or not the VideoController has been initialized, if it has then dispose(), otherwise don't.

@override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

CodePudding user response:

A simple solution might be to set a flag to true when it's initialized, and check that in your dispose method (I am aware that this should be a comment, but I don't have 50 rep).

  • Related