There are similar answers to the above question to use preload_page_view package but I am facing issues with it.
I tried two below methods with and without package
with package:
return Scaffold(
body: PreloadPageView.builder(
controller: _controller,
preloadPagesCount: 3,
scrollDirection: Axis.vertical,
itemCount: 10,
itemBuilder: (context, i) {
return VideoInit(
index: i,
videoUrl: sampleVideo[i],
);
}),
);
without package, I did this trick: by providing viewportFraction
return Scaffold(
body: PageView.builder(
allowImplicitScrolling: true,
controller: PageController(viewportFraction: 0.999),
itemCount: 3,
itemBuilder: (context, i) {
return VideoInit(
index: i,
videoUrl: sampleVideo[i],
);
}),
);
code for the video player is:
late VideoPlayerController _controller;
bool initialized = false;
initiliazeVideo() {
_controller = VideoPlayerController.network(
widget.videoUrl)
..initialize().then((_) {
if (mounted) {
setState(() {
_controller.setLooping(true);
_controller.pause();
initialized = true;
});
}
});
}
@override
void initState() {
initiliazeVideo();
super.initState();
}
@override
void dispose() {
if (initialized) {
initialized = false;
_controller.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return VisibilityDetector(
onVisibilityChanged: (info) {
if (info.visibleFraction > 0.5) {
if (initialized) {
_controller.play();
}
} else if (info.visibleFraction < 0.4) {
if (initialized) {
_controller.pause();
_controller.seekTo(Duration.zero);
}
}
},
key: UniqueKey(),
child: initialized
? SizedBox.expand(
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: _controller.value.size.width,
height: _controller.value.size.height,
child: VideoPlayer(_controller),
),
),
)
: const Center(child: CircularProgressIndicator()),
);
The issue with the above method is when a user tries to use the volume button and swipe the volume indicator to adjust the volume on android, the video starts lagging
https://www.dropbox.com/s/z7t2fvszd8p9f2y/VID_20220115124459.mp4?dl=0
What could be an alternative way to fix this?
Edit/Update
The lag is there if I use a listViewBuilder even. If there's a single video in a page view or list view, there's no such issue. I think this is because of the initialization of multiple video controllers.
Any suggestions for an alternative ways to achieve the required goal?