I want to play the video list sequentially using video_player. It should be able to play the next video automatically when the video ends.
I can detect when the video ends. But then I don't know how to play the next video. How can I initialize a new controller again after dispose previous controller?
Can someone tell me about this?
class VideoPlayingScreen extends StatefulWidget {
VideoPlayingScreen({
Key? key,
}) : super(key: key);
@override
State<VideoPlayingScreen> createState() => _VideoPlayingScreenState();
}
class _VideoPlayingScreenState extends State<VideoPlayingScreen> {
late VideoPlayerController _videoPlayer;
List<VideoSet> _videoSets = [];
int _playIndex = 0;
bool _isPlaying = false;
bool _isEnd = false;
Duration? _duration;
Duration? _position;
@override
void initState() {
_videoPlayer =
VideoPlayerController.file(File(_videoSets[_playIndex].video))
..addListener(() {
// setState(() {});
// new test
final bool isPlaying = _videoPlayer.value.isPlaying;
if (isPlaying != _isPlaying) {
setState(() {
_isPlaying = isPlaying;
});
}
Timer.run(() {
// current position
setState(() {
_position = _videoPlayer.value.position;
});
setState(() {
_duration = _videoPlayer.value.duration;
});
// detect end event
_duration?.compareTo(_position!) == 0 ||
_duration?.compareTo(_position!) == -1
? setState(() {
_isEnd = true;
logger.d("complete, next video");
// TODO
_videoPlayer.dispose();
// back first video
if (_playIndex >= _videoSets.length - 1) {
_playIndex = 0;
logger.d("First Video");
// TODO Next Video Play
} else {
_playIndex++;
}
})
: setState(() {
_isEnd = false;
});
});
})
..initialize().then((_) {
_videoPlayer.play();
setState(() {});
});
super.initState();
}
@override
void dispose() {
_videoPlayer.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: InkWell(
onTap: () {
Get.back();
},
// TODO video player
child: Center(
child: _videoPlayer.value.isInitialized
? VideoPlayer(_videoPlayer)
: Container(),
),
),
// video controller test
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_videoPlayer.value.isPlaying
? _videoPlayer.pause()
: _videoPlayer.play();
});
},
child: Icon(
_videoPlayer.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
);
}
}