Skip to content

Instantly share code, notes, and snippets.

@hman278
Created January 29, 2022 13:34
Show Gist options
  • Save hman278/2875b80d786f04ea79845c3e1fa2b724 to your computer and use it in GitHub Desktop.
Save hman278/2875b80d786f04ea79845c3e1fa2b724 to your computer and use it in GitHub Desktop.
Simple Bloc Counter App Flutter
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
void main() {
runApp(const MyApp());
}
abstract class CounterEvent extends Equatable {
@override
List<Object> get props => [];
}
class CounterIncrementEvent extends CounterEvent {}
class CounterDecrementEvent extends CounterEvent {}
class CounterState extends Equatable {
final int counter;
const CounterState({required this.counter}) : super();
@override
List<Object> get props => [counter];
}
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(const CounterState(counter: 0)) {
on<CounterIncrementEvent>(
(CounterIncrementEvent event, Emitter<CounterState> emit) =>
emit(CounterState(counter: state.counter + 1)));
on<CounterDecrementEvent>(
(CounterDecrementEvent event, Emitter<CounterState> emit) =>
emit(CounterState(counter: state.counter - 1)));
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter App using Bloc',
home: BlocProvider<CounterBloc>(
create: (_) => CounterBloc(), child: const App()));
}
}
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final counter = context.select((CounterBloc bloc) => bloc.state.counter);
return Scaffold(
appBar: AppBar(),
body: Center(
child:
Text(counter.toString(), style: const TextStyle(fontSize: 70))),
floatingActionButton:
BlocBuilder<CounterBloc, CounterState>(builder: (context, state) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
context.read<CounterBloc>().add(CounterIncrementEvent());
}),
FloatingActionButton(
child: const Icon(Icons.remove),
onPressed: () {
context.read<CounterBloc>().add(CounterDecrementEvent());
})
]);
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment