在下面显示的代码中,在获取BuildContext对象后,dispatch事件从build方法内部调用。如果我希望在initState方法本身开始处理时分派事件怎么办?
如果我使用didChangeDependencies方法,那么我会得到以下错误: BlocProvider.of()使用不包含FileManagerBloc类型Bloc的上下文进行调用。如何解决?
如果我使用didChangeDependencies方法,那么我会得到以下错误: BlocProvider.of()使用不包含FileManagerBloc类型Bloc的上下文进行调用。如何解决?
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocProvider<FileManagerBloc>(
builder: (context)=>FileManagerBloc(),
child: SafeArea(
child: Container(
child: Column(
children: <Widget>[
Container(color: Colors.blueGrey, child: TopMenuBar()),
Expanded(
child: BlocBuilder<FileManagerBloc,FileManagerState>(
builder: (context , state){
return GridView.count(
scrollDirection: Axis.vertical,
physics: ScrollPhysics(),
crossAxisCount: 3,
crossAxisSpacing: 10,
children: getFilesListWidget(context , state),
);
},
),
)
],
),
),
),
));
}
@override
void dispose() {
super.dispose();
}
@override
void didChangeDependencies() {
logger.i('Did change dependency Called');
final FileManagerBloc bloc = BlocProvider.of<FileManagerBloc>(context) ;
Messenger.sendGetHomeDir()
.then((path) async {
final files = await Messenger.sendListDir(path);
bloc.dispatch(SetCurrentWorkingDir(path)) ;
bloc.dispatch(UpdateFileSystemCacheMapping(path , files)) ;
});
}
didChangeDependencies
中使用它。在父部件中,我有BlocProvider
,所以我可以在子部件中访问 bloc。我使用它来触发事件,每当我导航到特定视图时都会使用counterBloc.add(...)
。 - user3056783