Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 检查无状态小部件是否在颤振中处理_Dart_Flutter_Dispose - Fatal编程技术网

Dart 检查无状态小部件是否在颤振中处理

Dart 检查无状态小部件是否在颤振中处理,dart,flutter,dispose,Dart,Flutter,Dispose,构建无状态小部件时,我使用以下代码按顺序播放一些声音: 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(co

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

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

dispose是State中的一个方法,因此您应该使用StatefulWidgetI已将小部件更改为stateful小部件,并重写“dispose”方法以更改“closed”值,它可以工作,但此解决方案是否减少了他们需要从关闭按钮更改“closed”值的次数,但我正在寻找一种避免声明“closed”变量的方法,并在以后所有调用之后进行“if”检查。我需要一种方法来取消以后的所有调用。@diegoveloper当我在“dispose”方法中处理_audioPlayer时,以防我用
Navigator.pop(上下文)关闭当前页面
每件事都很好,但是当我在当前路由(包含播放声音方法)的顶部推一个新路由时,dispose方法没有被调用,您有什么建议来处理这种情况吗?默认情况下,当您将路由推到它的顶部时,
MaterialPage路由
将不会被处理。如果要在非顶级路由时对其进行处理,则在创建播放音频的路由时,必须将
maintaintState
设置为false。有关更多信息,请参阅。在
StatelessWidget
中是否有相同的方法?调用
super.dispose()应该是方法的最后一行。