Last active
May 9, 2024 13:42
-
-
Save felangel/fc8230776591f0297e6a1d1b5ef46a6c to your computer and use it in GitHub Desktop.
Flutter Bloc Counter Example
This file contains hidden or 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:flutter_bloc/flutter_bloc.dart'; | |
void main() => runApp(App()); | |
abstract class CounterEvent {} | |
class Increment extends CounterEvent {} | |
class CounterBloc extends Bloc<CounterEvent, int> { | |
CounterBloc() : super(0) { | |
on<Increment>((event, emit) => emit(state + 1)); | |
} | |
} | |
class App extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: BlocProvider( | |
create: (_) => CounterBloc(), | |
child: CounterPage(), | |
), | |
); | |
} | |
} | |
class CounterPage extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: const Text('Counter')), | |
body: Center( | |
child: BlocBuilder<CounterBloc, int>( | |
builder: (context, count) { | |
return Text('$count', style: Theme.of(context).textTheme.headline1); | |
}, | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
child: const Icon(Icons.add), | |
onPressed: () => context.read<CounterBloc>().add(Increment()), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment