Skip to content

Instantly share code, notes, and snippets.

@thaihuynhxyz
Forked from felangel/main.dart
Last active September 5, 2020 02:23
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 thaihuynhxyz/bf7b280f3e068b32c84189b4dedbc5a4 to your computer and use it in GitHub Desktop.
Save thaihuynhxyz/bf7b280f3e068b32c84189b4dedbc5a4 to your computer and use it in GitHub Desktop.
[flutter_bloc_recipes] Navigation: Routes
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:meta/meta.dart';
void main() {
runApp(
BlocProvider(
create: (context) => MyBloc(),
child: MyApp(),
),
);
}
enum MyEvent { eventA, eventB, eventC }
@immutable
abstract class MyState {}
class StateA extends MyState {}
class StateB extends MyState {}
class StateC extends MyState {}
class MyBloc extends Bloc<MyEvent, MyState> {
MyBloc() : super(StateA());
@override
Stream<MyState> mapEventToState(MyEvent event) async* {
switch (event) {
case MyEvent.eventA:
yield StateA();
break;
case MyEvent.eventB:
yield StateB();
break;
case MyEvent.eventC:
yield StateC();
break;
}
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (context) => PageA(),
'/pageB': (context) => PageB(),
'/pageC': (context) => PageC(),
},
initialRoute: '/',
);
}
}
class PageA extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocListener<MyBloc, MyState>(
listener: (context, state) {
if (state is StateB) {
Navigator.of(context).pushNamed('/pageB');
} else if (state is StateC) {
Navigator.of(context).pushNamed('/pageC');
}
},
child: Scaffold(
appBar: AppBar(
title: Text('Page A'),
),
body: Center(
child: RaisedButton(
child: Text('Go to PageB'),
onPressed: () {
BlocProvider.of<MyBloc>(context).add(MyEvent.eventB);
},
),
),
),
);
}
}
class PageB extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocListener<MyBloc, MyState>(
listener: (context, state) {
if (state is StateC) {
Navigator.of(context).pushNamed('/pageC');
}
},
child: Scaffold(
appBar: AppBar(
title: Text('Page B'),
),
body: Center(
child: RaisedButton(
child: Text('Go to PageC'),
onPressed: () {
BlocProvider.of<MyBloc>(context).add(MyEvent.eventC);
},
),
),
),
);
}
}
class PageC extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Page C'),
),
body: Center(
child: RaisedButton(
child: Text('Pop'),
onPressed: () {
Navigator.of(context).pop();
},
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment