在 dispose 方法中访问 BlocProvider.of<Bloc>(context)

access BlocProvider.of<Bloc>(context) in dispose method

有人知道我该怎么做吗?

我的代码:

  @override
  void dispose() {
    final FiltersBloc filtersBloc = 
       BlocProvider.of<FiltersBloc>(context);
    super.dispose();
  }

错误是:

flutter:         BlocProvider.of() called with a context that does not contain a Bloc of type FiltersBloc.
flutter:         No ancestor could be found starting from the context that was passed to
flutter: BlocProvider.of<FiltersBloc>().
flutter:
flutter:         This can happen if:
flutter:         1. The context you used comes from a widget above the BlocProvider.
flutter:         2. You used MultiBlocProvider and didn't explicity provide the BlocProvider types.
flutter:
flutter:         Good: BlocProvider<FiltersBloc>(builder: (context) => FiltersBloc())
flutter:         Bad: BlocProvider(builder: (context) => FiltersBloc()).
flutter:
flutter:         The context used was: FiltersDrawer(dirty, state: _FiltersDrawerState#86e8a)

此外,如果我按照错误代码改用final filtersBloc = BlocProvider<FiltersBloc>(builder: (context) => FiltersBloc()),我就不能再调用filtersBloc.dispatch()了。

我知道对于 initState,我们可以 didChangeDependencies 代替。但是我找不到 dispose 的等价物。

如有任何帮助,我们将不胜感激。谢谢!

BlockProvider 需要初始化上下文。您可以在屏幕的 Widget build()

上初始化它
late FiltersBloc filtersBloc;

@override
Widget build(BuildContext context){
  filtersBloc = BlocProvider.of<FiltersBloc>(context);
  return ...
}

...然后在 dispose()

上调用所需的方法
@override
void dispose() {
  filtersBloc.dispatch();
  super.dispose();
}

一个更详细的小方法:

听起来很安全,你可以使用@Omatt 回答。

null safety不完善,可以使用以下方法:

在class中声明一个静态变量,并在initbuild中赋值如下:

class MyAwesomeWidget extends StatefulWidget {
  const MyAwesomeWidget({
    Key key,
  });

  @override
  _MyAwesomeWidgetState createState() => _MyAwesomeWidgetState();
}

class _MyAwesomeWidgetState extends State<MyAwesomeWidget> {
  FiltersBloc filtersBloc;

  @override
  void initState() {
    super.initState();
    new Future.delayed(Duration.zero, () {
      filterBloc = BlocProvider.of<FiltersBloc>(context);
    });
  }

  @override
  void dispose() {
    filterBloc.myFunction();
    super.dispose();
  }
}