how to access flutter bloc in the initState method?
The problem is that you are initializing the instance of FileManagerBloc
inside the BlocProvider
which is, of course inaccessible to the parent widget. I know that helps with automatic cleanup of the Bloc
but if you want to access it inside initState
or didChangeDependencies
then you have to initialize it at the parent level like so,
FileManagerBloc _fileManagerBloc;@overridevoid 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)) ; }); }
alternatively, if FileManagerBloc
was provided/initialized at a grandparent Widget
then it could easily be accessible at this
level through BlocProvider.of<CounterBloc>(context);