I'm using provider
with video_player
to manage the state.
VideoProvider has:
videoPlayerController = VideoPlayerController.network(...);
which I frequently change when the user switches to a new video (same screen). If I directly assign a new VideoPlayerController.network(...)
into the videoPlayerController
, the old video will still play and you can hear the sound. The workaround is to videoPlayerController.pause()
then assign a new VideoPlayerCOntroller.network
afterwards.
Is the previous Video being disposed by GC? Are there any performance issues with this? I want to get rid of the previous video and the resources used before switching to a new one. I can't videoPlayerController.dispose()
before switching because it causes an error.
When you call dispose
your controller is still being used by VideoPlayer widget. First, you need to make sure that it's not used anymore (setting controller in state to null) and AFTER that you call dispose.
I'm not sure about your state management via Provider, but I'll give you an example how to do this with regular State.
VideoPlayerController _controller;
void _initController(String link) {
_controller = VideoPlayerController.network(link)
..initialize().then((_) {
setState(() {});
});
}
Future<void> _onControllerChange(String link) async {
if (_controller == null) {
// If there was no controller, just create a new one
_initController(link);
} else {
// If there was a controller, we need to dispose of the old one first
final oldController = _controller;
// Registering a callback for the end of next frame
// to dispose of an old controller
// (which won't be used anymore after calling setState)
WidgetsBinding.instance.addPostFrameCallback((_) async {
await oldController.dispose();
// Initing new controller
_initController(link);
});
// Making sure that controller is not used by setting it to null
setState(() {
_controller = null;
});
}
}