有人知道我该怎么做吗?
我的代码:
@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
。但是我找不到等价物来处理。
任何帮助将不胜感激。谢谢!
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答案。
不健全的空安全,可以使用以下方法:
在类中声明一个静态变量,并在init或build中分配它,如下所示:
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();
}
}