Flutter video_player处置 [英] Flutter video_player dispose
问题描述
我正在将 provider
与 video_player
一起使用来管理状态。
I'm using provider
with video_player
to manage the state.
VideoProvider具有:
VideoProvider has:
videoPlayerController = VideoPlayerController.network(...);
当用户切换到新视频(同一屏幕)时,我经常更改它。如果我直接将新的 VideoPlayerController.network(...)
分配给 videoPlayerController
,则旧视频仍会播放您可以听到声音。解决方法是到 videoPlayerController.pause()
,然后分配新的 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.
以前的视频是否由GC处理?这有任何性能问题吗?我想摆脱以前的视频和切换到新视频之前使用的资源。切换之前,我不能 videoPlayerController.dispose()
,因为它会导致错误。
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.
推荐答案
调用 dispose
时, VideoPlayer 小部件仍在使用您的控制器。首先,您需要确保不再使用它(将controller的状态设置为null),然后再调用dispose。
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.
我不确定您是否可以通过Provider进行状态管理,但我将举例说明如何使用常规State。
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;
});
}
}
这篇关于Flutter video_player处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!