Guest User

Untitled

a guest
Mar 27th, 2020
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 2.19 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_bloc/flutter_bloc.dart';
  3.  
  4.  
  5.  
  6. enum CounterEvent { increment, decrement }
  7.  
  8. class CounterBloc extends Bloc<CounterEvent, int> {
  9.   @override
  10.   int get initialState => 0;
  11.  
  12.   @override
  13.   Stream<int> mapEventToState(CounterEvent event) async* {
  14.     switch (event) {
  15.       case CounterEvent.decrement:
  16.         print(state - 1);
  17.         yield state - 1;
  18.         break;
  19.       case CounterEvent.increment:
  20.         print(state + 1);
  21.  
  22.         yield state + 1;
  23.         break;
  24.     }
  25.   }
  26. }
  27.  
  28. void main() => runApp(MyApp());
  29.  
  30. class MyApp extends StatelessWidget {
  31.   @override
  32.   Widget build(BuildContext context) {
  33.     return MaterialApp(
  34.       title: 'Flutter Demo',
  35.       home: BlocProvider<CounterBloc>(
  36.         create: (context) => CounterBloc(),
  37.         child: CounterPage(),
  38.       ),
  39.     );
  40.   }
  41. }
  42.  
  43. class CounterPage extends StatelessWidget {
  44.   @override
  45.   Widget build(BuildContext context) {
  46.     final CounterBloc counterBloc = BlocProvider.of<CounterBloc>(context);
  47.  
  48.     return Scaffold(
  49.       appBar: AppBar(title: Text('Counter')),
  50.       body: Center(
  51.         child: BlocBuilder<CounterBloc, int>(bloc: BlocProvider.of<CounterBloc>(context),
  52.           builder: (context, count) {
  53.             return Text(
  54.               '${count}',
  55.               style: TextStyle(fontSize: 24.0),
  56.             );
  57.           },
  58.         ),
  59.       ),
  60.       floatingActionButton: Column(
  61.         crossAxisAlignment: CrossAxisAlignment.end,
  62.         mainAxisAlignment: MainAxisAlignment.end,
  63.         children: <Widget>[
  64.           Padding(
  65.             padding: EdgeInsets.symmetric(vertical: 5.0),
  66.             child: FloatingActionButton(
  67.               child: Icon(Icons.add),
  68.               onPressed: () {
  69.                 counterBloc.add(CounterEvent.increment);
  70.               },
  71.             ),
  72.           ),
  73.           Padding(
  74.             padding: EdgeInsets.symmetric(vertical: 5.0),
  75.             child: FloatingActionButton(
  76.               child: Icon(Icons.remove),
  77.               onPressed: () {
  78.                 counterBloc.add(CounterEvent.decrement);
  79.               },
  80.             ),
  81.           ),
  82.         ],
  83.       ),
  84.     );
  85.   }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment