Skip to content

Instantly share code, notes, and snippets.

@saliouseck2009
Created February 18, 2022 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saliouseck2009/9232ef96df2309fcf0c399c3e2a92d29 to your computer and use it in GitHub Desktop.
Save saliouseck2009/9232ef96df2309fcf0c399c3e2a92d29 to your computer and use it in GitHub Desktop.
bloc navigation using builder
void main() {
runApp(
BlocProvider(
create: (context) => MyBloc(),
child: MyApp(),
),
);
}
@immutable
abstract class MyEvent {}
class EventA extends MyEvent {}
class EventB extends MyEvent {}
@immutable
abstract class MyState {}
class StateA extends MyState {}
class StateB extends MyState {}
class MyBloc extends Bloc<MyEvent, MyState> {
MyBloc() : super(StateA()) {
on<EventA>((event, emit) => emit(StateA()));
on<EventB>((event, emit) => emit(StateB()));
}
}
### methode 1: use blocBuilder on materialApp and emit the state you want StateA for Page A
Widget build(BuildContext context) {
return MaterialApp(
home: BlocBuilder<MyBloc, MyState>(
builder: (_, state) => state is StateA ? PageA() : PageB(),
),
);
}
### methode 2 : we can also use the BlocListener to manage it
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (context) => PageA(),
'/pageB': (context) => PageB(),
},
initialRoute: '/',
);
}
}
return BlocListener<MyBloc, MyState>(
listener: (context, state) {
if (state is StateB) {
Navigator.of(context).pushNamed('/pageB');
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment