I am developing an APP using Fluter. In the APP a have a list of PageViews and each PageView will load and play a video when it appears. Any PageView will stop playing the video when it disappears. Now I have a question. When I slowly slide between PageViews, there will be two PageView at the same time. Each PageView appears a part. But all the two PageView are playing video. I want to know whether I can check the current PageView totally disappears, then I stop playing the video. And when the next PageView is totally showed, it begins to play video. So it will not play videos in two PageView at the same time. Anyone can help me?
import 'package:video_player/video_player.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MultiplePage(),
);
}
}
class MultiplePage extends StatefulWidget {
@override
_MultiplePageState createState() => _MultiplePageState();
}
class _MultiplePageState extends State<MultiplePage> {
PageController _controller;
void scrollListener() {
if (_controller.page == _controller.page.roundToDouble()) {
print(_controller.page);
}
}
@override
void initState() {
super.initState();
_controller = PageController()..addListener(scrollListener);
}
@override
Widget build(BuildContext context) {
return PageView.builder(
controller: _controller,
scrollDirection: Axis.vertical,
itemBuilder: (context, position) {
return VideoApp();
},
);
}
}
class VideoApp extends StatefulWidget {
@override
_VideoAppState createState() => _VideoAppState();
}
class _VideoAppState extends State<VideoApp> {
VideoPlayerController _controller;
@override
void initState() {
super.initState();
_controller = VideoPlayerController.network(
'http://www.sample-videos.com/video123/mp4/720/big_buck_bunny_720p_20mb.mp4')
..initialize().then((_) {
// Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
setState(() {
_controller.play();
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Video Demo',
home: Scaffold(
body: Center(
child: _controller.value.initialized
? AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller),
)
: Container(),
),
),
);
}
@override
void dispose() {
super.dispose();
_controller.pause();
_controller.dispose();
}
}