在下面显示的代码中,在获取 BuildContext 对象后从 build 方法中调用 dispatch 事件。如果我希望做的是在 initState 方法本身内的页面开始处理期间分派事件怎么办?
如果我使用 didChangeDependencies 方法,那么我会收到这个错误:
BlocProvider.of() called with a context that does not contain a Bloc of type FileManagerBloc.如何解决这个问题?
@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)) ;
});
}
Run Code Online (Sandbox Code Playgroud)
问题是您正在初始化FileManagerBloc内部的实例,BlocProvider这当然是父小部件无法访问的。我知道这有助于自动清理,Bloc但如果你想在内部访问它,initState或者didChangeDependencies你必须像这样在父级初始化它,
FileManagerBloc _fileManagerBloc;
@override
void initState() {
super.initState();
_fileManagerBloc= FileManagerBloc();
_fileManagerBloc.dispatch(LoadEducation());
}
@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() {
_fileManagerBloc.dispose();
super.dispose();
}
@override
void didChangeDependencies() {
logger.i('Did change dependency Called');
Messenger.sendGetHomeDir()
.then((path) async {
final files = await Messenger.sendListDir(path);
_fileManagerBloc.dispatch(SetCurrentWorkingDir(path)) ;
_fileManagerBloc.dispatch(UpdateFileSystemCacheMapping(path , files)) ;
});
}
Run Code Online (Sandbox Code Playgroud)
或者,如果FileManagerBloc在祖父母处提供/初始化,Widget则可以this通过以下方式轻松访问BlocProvider.of<CounterBloc>(context);
您可以在didChangeDependenciesmethod 而不是 中使用它initState。
例子
@override
void didChangeDependencies() {
final CounterBloc counterBloc = BlocProvider.of<CounterBloc>(context);
//do whatever you want with the bloc here.
super.didChangeDependencies();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9036 次 |
| 最近记录: |