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';
- class CounterState {
- int counter;
- static final CounterState _state=CounterState._();
- CounterState._(){
- counter=0;
- }
- factory CounterState() {
- return _state;
- }
- }
- abstract class CounterEvent {}
- class IncrementEvent extends CounterEvent {}
- class DecrementEvent extends CounterEvent {}
- class CounterBloc extends Bloc<CounterEvent, CounterState> {
- @override
- CounterState get initialState => CounterState();
- @override
- Stream<CounterState> mapEventToState(CounterEvent event) async* {
- if (event is IncrementEvent) {
- yield state..counter +=1;
- } else if (event.runtimeType == DecrementEvent) {
- yield state..counter -= 1;
- }
- }
- }
- 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, CounterState>(
- builder: (context, count) {
- return Text(
- '${count.counter}',
- 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(IncrementEvent());
- },
- ),
- ),
- Padding(
- padding: EdgeInsets.symmetric(vertical: 5.0),
- child: FloatingActionButton(
- child: Icon(Icons.remove),
- onPressed: () {
- counterBloc.add(DecrementEvent());
- },
- ),
- ),
- ],
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment