【问题标题】:Check if Stateless widget is disposed in flutter检查无状态小部件是否在颤振中处理
【发布时间】:2018-10-21 17:10:26
【问题描述】:

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

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

如果我的小部件关闭,是否有更好的方法来停止异步方法?

【问题讨论】:

  • dispose 是一个来自 State 的方法,所以你应该使用 StatefulWidget
  • 我已将小部件更改为有状态小部件并覆盖“dispose”方法以更改“关闭”值并且它可以工作,但是这种解决方案减少了他们需要从关闭按钮更改“关闭”值,但我正在寻找一种方法来避免声明“关闭”变量并在所有未来调用之后进行“if”检查。我需要一种方法来取消所有未来的电话。@diegoveloper

标签: dart flutter dispose


【解决方案1】:

如果您将小部件更改为 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' 方法中处理 _audioPlayer 时,以防我用Navigator.pop(context); 关闭当前页面,一切正常,但是当我在顶部推新路线时当前路由(包含播放声音方法)dispose方法未调用,请问您有什么建议来处理这种情况吗?
  • 默认情况下,MaterialPageRoute 不会在您将路由推送到其顶部时释放。如果您希望它在不是顶级路由时进行处理,则必须在创建正在播放音频的路由时将 maintainState 设置为 false。请参阅docs 了解更多信息。
  • StatelessWidget 有什么方法可以做同样的事情吗?
  • super.dispose(); 的调用应该是方法的最后一行。 If you override this, make sure to end your method with a call to super.dispose().
猜你喜欢
  • 2022-11-12
  • 2019-08-28
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
  • 2020-07-29
  • 1970-01-01
  • 2019-11-29
  • 2020-04-20
相关资源
最近更新 更多