当我的无状态小部件被构建时,我使用以下代码按顺序播放一些声音:
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);
如果用户在播放音频之前关闭当前的小部件,那么即使使用以下代码关闭了当前路由,音频仍然会继续播放:
Navigator.pop(context);
我的解决方法是使用一个布尔变量来表示关闭操作是否已完成。
播放声音的代码:
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();
如果我的小部件关闭了,是否有更好的方法来停止异步方法?