Created
April 16, 2024 14:45
-
-
Save Khanin-devmode/8a49ef8fdecccf12b397b84dbd8b6ec9 to your computer and use it in GitHub Desktop.
Minimal counter app with bloc library
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:flutter_bloc/flutter_bloc.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
// This widget is the root of your application. | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), | |
useMaterial3: true, | |
), | |
home: BlocProvider( | |
create: (_) => CounterCubit(), | |
child: const MyHomePage(title: 'Flutter Demo Home Page')), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
const MyHomePage({super.key, required this.title}); | |
final String title; | |
@override | |
State<MyHomePage> createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
@override | |
Widget build(BuildContext context) { | |
final textTheme = Theme.of(context).textTheme; | |
return Scaffold( | |
appBar: AppBar( | |
backgroundColor: Theme.of(context).colorScheme.inversePrimary, | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
const Text( | |
'You have pushed the button this many times:', | |
), | |
BlocBuilder<CounterCubit, int>( | |
builder: (context, state) { | |
return Text('$state', style: textTheme.headlineMedium); | |
}, | |
), | |
], | |
), | |
), | |
floatingActionButton: Column( | |
mainAxisAlignment: MainAxisAlignment.end, | |
crossAxisAlignment: CrossAxisAlignment.end, | |
children: <Widget>[ | |
FloatingActionButton( | |
child: const Icon(Icons.add), | |
// onPressed: () => context.read<CounterCubit>().increment(), | |
onPressed: () => context.read<CounterCubit>().increment(), | |
), | |
const SizedBox(height: 8), | |
FloatingActionButton( | |
child: const Icon(Icons.remove), | |
onPressed: () => context.read<CounterCubit>().decrement(), | |
), | |
], | |
), | |
); | |
} | |
} | |
class CounterCubit extends Cubit<int> { | |
/// {@macro counter_cubit} | |
CounterCubit() : super(0); | |
/// Add 1 to the current state. | |
void increment() => emit(state + 1); | |
/// Subtract 1 from the current state. | |
void decrement() => emit(state - 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment