在构建无状态小部件时,我使用以下代码按顺序播放一些声音:

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);

当用户在播放完声音之前关闭当前Widget时,即使使用以下代码关闭当前路由,声音仍然有效:

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();
}

Dart相关问答推荐

您如何在元素中设置自定义元素标签的样式?

VSCode Flutter Dart 启动慢的建议

我可以动态应用 Dart 的字符串插值吗?

InheritedWidget - 在 navigator.push 之后在 null 上调用 getter

Flutter 中的 authStateChanges

如何在Flatter中将图表线 colored颜色 更改为自定义 colored颜色 代码值

了解Dart private class

Flutter-创建一个倒计时(countdown)小部件

如何在 Flutter 中管理 Firebase 身份验证状态?

在 Dart 中使用带有 Future 的循环

Flutter 中 ChangeNotifier 的构建器小部件

如何在imageprovider类型中传递图像资源?

你如何在 Dart 中将月份的日期格式化为11th、21st或23rd?

在字符串中查找字母 (charAt)

Dart 构造函数与静态方法;例如,为什么 int.parse() 不是工厂构造函数?

如何在 Dart 2 中将 List 更改为 List

在 Dart 中,List.from 和 .of 以及 Map.from 和 .of 有什么区别?

我应该更喜欢迭代 Map.entries 还是 Map.values?

Dart 中使用的包命名约定是什么?

你如何在 Dart 中对异常进行单元测试?