I am getting started with the BLoC pattern but I have a question:
1) Should you use the BloC pattern to determine if the routes should change?
Example: authentication object changes to unauthenticated
so the listeners should handle the route changes.
2) Should the BLoC pattern only be used for UI state and handle the route changes on UI changes?
Example: User clicks on login
and navigates to the home
screen.
I ask this question because I'm facing a problem where I don't have a central navigation management solution.
This code is in my BLoC now:
loggedIn.listen((AuthResponse user) {
currentUserSubject.add(user);
Navigator.pushReplacement(
_context,
PageRouteBuilder(
pageBuilder: (context, animation1, animation2) {
return HomePage();
},
transitionsBuilder: (context, animation, _, child) {
return new SlideTransition(
child: child,
position: new Tween<Offset>(
begin: const Offset(0.0, 1.0),
end: Offset.zero,
).animate(animation),
);
},
transitionDuration: Duration(milliseconds: 400),
),
);
}, onError: (error) {
Scaffold.of(_context).showSnackBar(new SnackBar(
content: new Text(error.message),
));
});
I see there are 2 Yes/No questions there (in contrast to W/H questions), and my answers are yes to both of them. The reason being that with BloC and navigation, you can actually recover the current screen if the app crashes (auto-save state and state recover must be in place, but it's another W/H question), and other nice features of BLoC/event-based state management (history snapshot, time machine, event replay, separate of concerns, testability, etc.)
I ask this question because I'm facing a problem where I don't have a central navigation management solution.
Is there anything I can help with regarding your problem?
What I'm currently doing is:
NavigatorBloc
that receive a NavigatorState
in the constructor and receive actions to navigate to different pages in your app Ex: GoToHomePageAction
, GoToRegisterPageAction
, NavigatorActionPop
.In your App widget you register the NavigatorBloc
and provide the navigator key attached to the MaterialApp
widget.
@override
Widget build(BuildContext context) {
return BlocProvider<NavigatorBloc>(
bloc: NavigatorBloc(navigatorKey: widget.navigatorKey),
child: MaterialApp(
navigatorKey: widget.navigatorKey,
title: 'Medicine Tracker',
theme: ThemeData(
primarySwatch: Colors.red,
scaffoldBackgroundColor: Colors.white
),
home: HomePage(),
),
);
}
Then in side your NavigatorBloc
you just check the the action and navigate to the desired page:
class NavigatorBloc extends Bloc<NavigatorAction, dynamic>{
final GlobalKey<NavigatorState> navigatorKey;
NavigatorBloc({this.navigatorKey});
@override
dynamic get initialState => 0;
@override
Stream<dynamic> mapEventToState(NavigatorAction event) async* {
if(event is NavigatorActionPop){
yield navigatorKey.currentState.pop();
}
}
}
Hope it help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With