If you want 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,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 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)) ; }); } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.