Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:flutter/material.dart';
- import 'package:flutter_bloc/flutter_bloc.dart';
- enum CounterEvent { increment, decrement }
- class CounterBloc extends Bloc<CounterEvent, int> {
- @override
- int get initialState => 0;
- @override
- Stream<int> mapEventToState(CounterEvent event) async* {
- switch (event) {
- case CounterEvent.decrement:
- print(state - 1);
- yield state - 1;
- break;
- case CounterEvent.increment:
- print(state + 1);
- yield state + 1;
- break;
- }
- }
- }
- void main() => runApp(MyApp());
- class MyApp extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- title: 'Flutter Demo',
- home: BlocProvider<CounterBloc>(
- create: (context) => CounterBloc(),
- child: CounterPage(),
- ),
- );
- }
- }
- class CounterPage extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- final CounterBloc counterBloc = BlocProvider.of<CounterBloc>(context);
- return Scaffold(
- appBar: AppBar(title: Text('Counter')),
- body: Center(
- child: BlocBuilder<CounterBloc, int>(bloc: BlocProvider.of<CounterBloc>(context),
- builder: (context, count) {
- return Text(
- '${count}',
- style: TextStyle(fontSize: 24.0),
- );
- },
- ),
- ),
- floatingActionButton: Column(
- crossAxisAlignment: CrossAxisAlignment.end,
- mainAxisAlignment: MainAxisAlignment.end,
- children: <Widget>[
- Padding(
- padding: EdgeInsets.symmetric(vertical: 5.0),
- child: FloatingActionButton(
- child: Icon(Icons.add),
- onPressed: () {
- counterBloc.add(CounterEvent.increment);
- },
- ),
- ),
- Padding(
- padding: EdgeInsets.symmetric(vertical: 5.0),
- child: FloatingActionButton(
- child: Icon(Icons.remove),
- onPressed: () {
- counterBloc.add(CounterEvent.decrement);
- },
- ),
- ),
- ],
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment