How to play a List of video in Flutter?

Bobson Lin picture Bobson Lin · Apr 2, 2019 · Viewed 11.7k times · Source

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?

Answer

Brownsoo Han picture Brownsoo Han · Apr 19, 2019

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(() {});
    });
}