Advertisement
Guest User

Untitled

a guest
Oct 13th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:meta/meta.dart';
  3. import 'package:bloc/bloc.dart';
  4. import 'package:flutter_bloc/flutter_bloc.dart';
  5.  
  6. void main() {
  7. runApp(
  8. BlocProvider(
  9. builder: (context) => MyBloc(),
  10. child: MyApp(),
  11. ),
  12. );
  13. }
  14.  
  15. enum MyEvent { eventA, eventB }
  16.  
  17. @immutable
  18. abstract class MyState {}
  19.  
  20. class StateA extends MyState {}
  21.  
  22. class StateB extends MyState {}
  23.  
  24. class MyBloc extends Bloc<MyEvent, MyState> {
  25. @override
  26. MyState get initialState => StateA();
  27.  
  28. @override
  29. Stream<MyState> mapEventToState(MyEvent event) async* {
  30. switch (event) {
  31. case MyEvent.eventA:
  32. yield StateA();
  33. break;
  34. case MyEvent.eventB:
  35. yield StateB();
  36. break;
  37. }
  38. }
  39. }
  40.  
  41. class MyApp extends StatelessWidget {
  42. @override
  43. Widget build(BuildContext context) {
  44. return MaterialApp(
  45. routes: {
  46. '/': (context) => PageA(),
  47. '/pageB': (context) => PageB(),
  48. },
  49. initialRoute: '/',
  50. );
  51. }
  52. }
  53.  
  54. class PageA extends StatelessWidget {
  55. @override
  56. Widget build(BuildContext context) {
  57. final myBloc = BlocProvider.of<MyBloc>(context);
  58. return BlocListener<MyBloc, MyState>(
  59. listener: (context, state) {
  60. if (state is StateB) {
  61. Navigator.of(context).pushNamed('/pageB');
  62. }
  63. },
  64. child: Scaffold(
  65. appBar: AppBar(
  66. title: Text('Page A'),
  67. ),
  68. body: Center(
  69. child: RaisedButton(
  70. child: Text('Go to PageB'),
  71. onPressed: () {
  72. myBloc.dispatch(MyEvent.eventB);
  73. },
  74. ),
  75. ),
  76. ),
  77. );
  78. }
  79. }
  80.  
  81. class PageB extends StatelessWidget {
  82. @override
  83. Widget build(BuildContext context) {
  84. return Scaffold(
  85. appBar: AppBar(
  86. title: Text('Page B'),
  87. ),
  88. body: Center(
  89. child: RaisedButton(
  90. child: Text('Pop'),
  91. onPressed: () {
  92. Navigator.of(context).pop();
  93. },
  94. ),
  95. ),
  96. );
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement