Last active
September 13, 2021 21:37
-
-
Save felangel/be891e73a7c91cdec9e7d5f035a61d5d to your computer and use it in GitHub Desktop.
Recipe: Bloc Access (Global)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:bloc/bloc.dart'; | |
import 'package:flutter_bloc/flutter_bloc.dart'; | |
class SimpleBlocObserver extends BlocObserver { | |
@override | |
void onEvent(Bloc bloc, Object event) { | |
super.onEvent(bloc, event); | |
print(event); | |
} | |
@override | |
void onTransition(Bloc bloc, Transition transition) { | |
super.onTransition(bloc, transition); | |
print(transition); | |
} | |
@override | |
void onError(BlocBase bloc, Object error, StackTrace stacktrace) { | |
super.onError(bloc, error, stacktrace); | |
print(error); | |
} | |
} | |
void main() { | |
Bloc.observer = SimpleBlocObserver(); | |
runApp(App()); | |
} | |
class App extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return BlocProvider( | |
create: (context) => CounterBloc(), | |
child: MaterialApp( | |
title: 'Flutter Demo', | |
home: CounterPage(), | |
), | |
); | |
} | |
} | |
class CounterPage extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text('Counter')), | |
body: Center( | |
child: CounterText(), | |
), | |
floatingActionButton: Column( | |
crossAxisAlignment: CrossAxisAlignment.end, | |
mainAxisAlignment: MainAxisAlignment.end, | |
children: <Widget>[ | |
Padding( | |
padding: EdgeInsets.symmetric(vertical: 5.0), | |
child: FloatingActionButton( | |
child: Icon(Icons.add), | |
onPressed: () { | |
context.read<CounterBloc>().add(Increment()); | |
}, | |
), | |
), | |
Padding( | |
padding: EdgeInsets.symmetric(vertical: 5.0), | |
child: FloatingActionButton( | |
child: Icon(Icons.remove), | |
onPressed: () { | |
context.read<CounterBloc>().add(Decrement()); | |
}, | |
), | |
), | |
], | |
), | |
); | |
} | |
} | |
class CounterText extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return BlocBuilder<CounterBloc, int>( | |
builder: (context, count) { | |
return Text('$count'); | |
}, | |
); | |
} | |
} | |
abstract class CounterEvent {} | |
class Increment extends CounterEvent {} | |
class Decrement extends CounterEvent {} | |
class CounterBloc extends Bloc<CounterEvent, int> { | |
CounterBloc() : super(0) { | |
on<Increment>((event, emit) => emit(state + 1)); | |
on<Decrement>((event, emit) => emit(state - 1)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To make this example work with flutter_bloc: ^4.0.0