Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a List of video in Flutter?

I'm using flutter video_player package to play a list of video.

List sourceList;

sourceList = [
  {
    "size": 69742504,
    "name": "lucky-roulette.mp4",
    "mimetype": "video/mp4",
  },
  {
    "size": 69742504,
    "name": "BigBuckBunny.mp4",
    "mimetype": "video/mp4",
  }
];

I've checked out this issue, and did some custom codes upon it.

void play() {
  log.fine("Now playing: $_nowPlayingUrl");
  _adController = VideoPlayerController.network(_nowPlayingUrl);
  _adController.initialize().then((_) => setState(() {}));
  _adController.play();
  _adController.addListener(checkIfVideoFinished);
}

void checkIfVideoFinished() {
  if (_adController == null ||
      _adController.value == null ||
      _adController.value.position == null ||
      _adController.value.duration == null) return;
  if (_adController.value.position.inSeconds ==
      _adController.value.duration.inSeconds) {
    _adController.removeListener(checkIfVideoFinished);
    _adController.dispose();
    // Change _nowPlayingIndex
    setState(() {
      _nowPlayingIndex = (_nowPlayingIndex + 1) % _totalIndex;
    });
    play();
  }
}

But use this code snippet would send out an exception Another exception was thrown: A VideoPlayerController was used after being disposed.

Is there a better way to play and loop a list of video in Flutter?

like image 705
Bobson Lin Avatar asked Apr 02 '19 03:04

Bobson Lin


2 Answers

Recently I tested video list example. please check the source in github FlutterVideoListSample. I think the video widget must be disposed.

In my case, I clear the old VideoPlayerController before initialize it. And I don't use chewie plugin that make new page in entering fullscreen so cannot handle the next video widget.

dependencies
video_player: '>=0.10.11+1 <2.0.0'
some code in FlutterVideoListSample
VideoPlayerController _controller;

void _initializeAndPlay(int index) async {
  print("_initializeAndPlay ---------> $index");
  final clip = _clips[index];
  final controller = VideoPlayerController.asset(clip.videoPath());
  final old = _controller;
  if (old != null) {
    old.removeListener(_onControllerUpdated);
    old.pause(); // mute instantly
  }
  _controller = controller;
  setState(() {
    debugPrint("---- controller changed");
  });

  controller
    ..initialize().then((_) {
      debugPrint("---- controller initialized");
      old?.dispose();
      _playingIndex = index;
      controller.addListener(_onControllerUpdated);
      controller.play();
      setState(() {});
    });
}
like image 112
Brownsoo Han Avatar answered Oct 12 '22 11:10

Brownsoo Han


You must call the video controller dispose method in Override dispose method. Need not call dispose method when removevideo.

like image 35
Akio Alex Avatar answered Oct 12 '22 12:10

Akio Alex