Reputation: 1572
I'm learning flutter by building app. I've implemented BLoC pattern
to call rest api and provide data to the widgets. However per my understanding this is some data for the view which needs it. I want to have Settings
button on most of the widgets where I can display current logged user information, able to change his language, theme, some specific selected data etc. Basically base state of the application. Is the BLoC pattern
the approach for that? Or there is better way to that?
If yes, what is the way to do that. How can I handle multiple StreamBuilder
, e.g. one for receiving the data from api and one to update the state?
I know I can do it dummy with singleton class and register it using get-it plugin
, but if there is better way I would skip this.
Upvotes: 1
Views: 568
Reputation: 1572
If anyone comes accross I've made it with flutter_bloc
plugin. BlocProvider
works on top of provider
package mentioned by @Fer Buero Trebino
class ApplicationStateBloc extends Cubit<ApplicationState> {
ApplicationStateBloc() : super(new ApplicationState());
void updateWhatEver(Whatever whatever) {
state.whatever = whatever;
emit(state);
}
ApplicationState getCurrentState() => state;
}
Then in order to not deal with context not having the providers and stuff, register it on application load
void main() {
setup();
runApp(
MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => ApplicationStateBloc()
)
],
child: App())
);
}
Then accessing the state in every widget is simple as
BlocProvider.of<ApplicationStateBloc>(context).getCurrentState()
Not sure if meets best practices, I'm open for comments, but for now it works.
Upvotes: 0
Reputation: 113
The recommendation of Google for managing state is to use the Provider Package. But always depends on what you need to do.
The author of Provider release a better version of provider called Riverpod. But I think is not ready for production yet.
Upvotes: 0