简体   繁体   English

检查 Stateless 小部件是否在 flutter 中被处理

[英]Check if Stateless widget is disposed in flutter

When my stateless widget built I play some sounds in sequence order by using this code:当我的无状态小部件构建时,我使用以下代码按顺序播放一些声音:

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

when the user closes the current widget before finish playing the sounds, The sounds still work even after closing the current route by using this code:当用户在完成播放声音之前关闭当前小部件时,即使在使用以下代码关闭当前路由后声音仍然有效:

Navigator.pop(context);

my workaround is to use a boolean variable to indicate if the closing action has done.我的解决方法是使用布尔变量来指示关闭操作是否已完成。

Playing sound code:播放声音代码:

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

Closing the current widget:关闭当前小部件:

closed = true;
_audioPlayer.stop();

Are there a better way to stop the async methods if my widget closed?如果我的小部件关闭,是否有更好的方法来停止异步方法?

If you change your widget to a StatefulWidget then you can have a function like the following:如果您将小部件更改为 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);
}

and then in the dispose method just dispose of the player:然后在 dispose 方法中处理播放器:

@override
void dispose() {
  _audioPlayer?.dispose();
  super.dispose();
}

The mounted getter is currently merged in master channel but it still not available in the stable channel. mounted getter 目前已合并到 master 频道中,但在稳定频道中仍不可用。

https://github.com/flutter/flutter/pull/111619 https://github.com/flutter/flutter/pull/111619

In the mean time, we have 2 option同时,我们有 2 个选项

  1. Use Stateful Widget directly (as accepted answer)直接使用 Stateful Widget(作为公认的答案)
  2. Implement a Stateful Widget wrapper with builder method to pass down the mounted getter also in a wrapper.使用 builder 方法实现一个有状态的 Widget 包装器,以在包装器中传递已mounted的 getter。

Wrapper widget包装小部件

import 'package:flutter/material.dart';

class PrimitiveWrapper<T> {
  T value;

  PrimitiveWrapper(this.value);
}

class MountedWrapper extends StatefulWidget {
  final Widget Function(BuildContext context, PrimitiveWrapper<bool> mounted) builder;

  const MountedWrapper({
    required this.builder,
    super.key,
  });

  @override
  State<MountedWrapper> createState() => _MountedWrapperState();
}

class _MountedWrapperState extends State<MountedWrapper> {
  @override
  Widget build(BuildContext context) {
    return widget.builder.call(context, PrimitiveWrapper(mounted));
  }
}

Usage用法

class SubmitBtn extends StatelessWidget {

  ...

  Future<void> onSubmit(WidgetRef ref, BuildContext context, PrimitiveWrapper<bool> mounted) async {
    ...

    await topicRepo.add(topic);

    if (!mounted.value) {
      return;
    }

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Created topic'),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MountedWrapper(
      builder: (context, mounted) {
        return Consumer(
          builder: (context, ref, child) {
            return ElevatedButton(
              onPressed: () {
                onSubmit(ref, context, mounted);
              },
              child: const Text('Create'),
            );
          },
        );
      },
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM