dart - 检查无状态小部件是否在颤振中处理
问题描述
当我的无状态小部件构建时,我使用以下代码按顺序播放一些声音:
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();
如果我的小部件关闭,是否有更好的方法来停止异步方法?
解决方案
如果您将小部件更改为 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);
}
然后在 dispose 方法中处理播放器:
@override
void dispose() {
_audioPlayer?.dispose();
super.dispose();
}
推荐阅读
- rx-java - ReactiveX - 单
单身 - javascript - 使用 jQuery 返回隐藏值
- spring-boot - 用于 JDBC 模板插入查询的 Mockito 测试用例
- python - 如何通过map函数将str转换为int?
- appium - 如果本机应用程序中的屏幕截图受到限制,如何在 APPIUM 中进行屏幕截图
- javascript - 我需要编写一个以小写字母开头,后跟小写字母和数字的 JS 正则表达式。长度可以是 25 个字符
- go - Golang 无法从恐慌中恢复 mgo.DialWithInfo
- wso2 - 通过代理服务访问端点时出现授权错误
- javascript - 对于奇数测试,按位 AND 运算符是否总是比模数更快?
- assembly - 寄存器值问题的小端表示