检查无状态小部件是否乱扔 [英] Check if Stateless widget is disposed in flutter
问题描述
构建无状态小部件时,我使用以下代码按顺序播放一些声音:
When my stateless widget built I play some sounds in sequence order by using this code:
await _audioPlayer.play(contentPath1, isLocal: true);
await Future.delayed(Duration(seconds: 4));
await _audioPlayer.play(contentPath2, isLocal: true);
await Future.delayed(Duration(seconds: 4));
await _audioPlayer.play(contentPath3, isLocal: true);
当用户在结束播放声音之前关闭当前小部件时,即使关闭了使用此代码的当前路线:
when the user closes the current widget before finish playing the sounds, The sounds still work even after closing the current route by using this code:
Navigator.pop(context);
我的解决方法是使用布尔变量来指示关闭操作是否完成。
my workaround is to use a boolean variable to indicate if the closing action has done.
播放声音代码:
await _audioPlayer.play(contentPath1, isLocal: true);
if (closed) return;
await Future.delayed(Duration(seconds: 4));
if (closed) return;
await _audioPlayer.play(contentPath2, isLocal: true);
if (closed) return;
await Future.delayed(Duration(seconds: 4));
if (closed) return;
await _audioPlayer.play(contentPath3, isLocal: true);
关闭当前小部件:
closed = true;
_audioPlayer.stop();
如果我的小部件关闭,还有更好的方法来停止异步方法吗?
Are there a better way to stop the async methods if my widget closed?
推荐答案
如果将窗口小部件更改为StatefulWidget,则可以具有如下功能:
If you change your widget to a StatefulWidget then you can have a function like the following:
void _playSounds() {
await _audioPlayer.play(contentPath1, isLocal: true);
await Future.delayed(Duration(seconds: 4));
if (!mounted) return;
await _audioPlayer.play(contentPath2, isLocal: true);
await Future.delayed(Duration(seconds: 4));
if (!mounted) return;
await _audioPlayer.play(contentPath3, isLocal: true);
}
,然后在dispose方法中处置玩家:
and then in the dispose method just dispose of the player:
@override
void dispose() {
super.dispose();
_audioPlayer?.dispose();
}
这篇关于检查无状态小部件是否乱扔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!