When trying to play two (or more) videos in Safari, the first video requires user interaction to play, so I added a play button. Then, when the next video widget appears, the video will start automatically even if the video controller was paused. Now the button shows the play icon but the video is already playing... How can I fix this?
Also it looks like the controller of the second video didn't add the listener since no print statement is executed (until the button is pressed).
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() => runApp(const VideoDemo());
class VideoDemo extends StatelessWidget {
const VideoDemo({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.first_page)),
Tab(icon: Icon(Icons.last_page)),
],
),
title: const Text('Video Demo'),
),
body: const TabBarView(
children: [
VideoWidget(),
VideoWidget(),
],
),
),
),
);
}
}
class VideoWidget extends StatefulWidget {
const VideoWidget({Key? key}) : super(key: key);
@override
_VideoWidgetState createState() => _VideoWidgetState();
}
class _VideoWidgetState extends State<VideoWidget> {
late VideoPlayerController _controller;
bool hasLoaded = false;
@override
void initState() {
super.initState();
_controller = VideoPlayerController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4')
..setLooping(true)
..addListener(videoListener)
..initialize().then((_) {
setState(() {
hasLoaded = true;
});
})
..pause(); // <-- PAUSE the video
}
@override
Widget build(BuildContext context) => Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: Colors.red,
child: Stack(
alignment: Alignment.center,
children: [
_controller.value.isInitialized
? VideoPlayer(_controller)
: const Center(child: CircularProgressIndicator()),
SizedBox(
height: 50,
width: 130,
child: ElevatedButton(
onPressed: () {
setState(() {
_controller.value.isPlaying
? _controller.pause()
: _controller.play();
});
},
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
)),
],
));
void videoListener() { // <-- Listener does not fire on second video until play button is pressed
if (hasLoaded) {
print("isPlaying: ${_controller.value.isPlaying}");
}
}
@override
void dispose() {
super.dispose();
_controller.dispose();
}
}