Skip to content

Instantly share code, notes, and snippets.

@felangel
Last active October 31, 2023 08:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felangel/fc8230776591f0297e6a1d1b5ef46a6c to your computer and use it in GitHub Desktop.
Save felangel/fc8230776591f0297e6a1d1b5ef46a6c to your computer and use it in GitHub Desktop.
Flutter Bloc Counter Example
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