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

当用户在播放完声音之前关闭当前小部件,使用此代码关闭当前路由后声音仍然有效:

Navigator.pop(context);

我的解决方法是使用 bool 变量来指示关闭操作是否已完成。

播放声音代码:

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

https://stackoverflow.com/questions/52917847/

相关文章:

dart - flutter 错误 : Could not find the correct Sco

dart - 具有水平列表和网格的 Flutter 可滚动主体作为子项

flutter - 加载数据时制作骨架屏幕的最简单方法

dart - Flutter 小部件测试 : StreamBuilder snapshot has

flutter - Flutter 中的可滚动底部工作表

flutter - 内置值对象的 setter 是什么

dart - 在初始化程序中只能访问静态成员。 Dart2.0

dart - 如何在没有 Scaffold.drawer 的情况下使用 Drawer?

ios - Flutter 在我的 Flutter 应用程序的根目录上构建 IOS 不起作用

android - 在 Flutter 中剪切文本效果