Flu*_*Dev 4 dispose dart flutter
构建我的无状态窗口小部件时,我使用以下代码按顺序播放一些声音:
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);
Run Code Online (Sandbox Code Playgroud)
当用户在结束播放声音之前关闭当前小部件时,即使使用以下代码关闭了当前路线,声音仍然起作用:
Navigator.pop(context);
Run Code Online (Sandbox Code Playgroud)
我的解决方法是使用布尔变量来指示关闭操作是否完成。
播放声音代码:
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);
Run Code Online (Sandbox Code Playgroud)
关闭当前小部件:
closed = true;
_audioPlayer.stop();
Run Code Online (Sandbox Code Playgroud)
如果我的小部件已关闭,是否有更好的方法来停止异步方法?
如果将窗口小部件更改为StatefulWidget,则可以具有如下功能:
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);
}
Run Code Online (Sandbox Code Playgroud)
然后在dispose方法中只处置播放器:
@override
void dispose() {
super.dispose();
_audioPlayer?.dispose();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4284 次 |
| 最近记录: |