This repository contains the source code for the tutorial Bloc Too Tough? Start with Cubit for a Smoother Ride! published on Medium. It demonstrates how to convert the default Flutter counter app to use Cubit state management, making state handling smoother and more scalable.
- Introduction
- Features
- Getting Started
- Dependencies
- Code Overview
- License
- Contribution Guidelines
- Contact
Welcome to the Cubit Counter App! This project showcases how you can manage state in a Flutter application using Cubit from the Bloc package, a lightweight alternative to setState()
that allows for better state management without the complexity of Bloc.
- 🛠 Built with Flutter and Cubit.
- 🚀 Easy to understand counter functionality demonstrating how Cubit works.
- 📈 Scalable state management compared to
setState()
.
-
Clone this repository:
git clone https://github.com/tech-ramakant/counter_app_with_cubit.git cd counter_app_with_cubit
-
Install the required dependencies:
flutter pub get
-
Run the app:
flutter run
This app uses the following packages:
- flutter_bloc: A predictable state management library that helps implement the Cubit pattern.
- flutter: The core framework for building natively compiled applications for mobile, web, and desktop.
To add these dependencies, ensure you have the following in your pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
flutter_bloc: ^8.0.0
Here’s what we changed from the default Flutter counter app:
- CounterCubit We created a CounterCubit class that extends Cubit. This class contains logic to manage the counter state:
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
}
- BlocProvider We wrap the MyApp widget with BlocProvider, providing the CounterCubit to the entire app:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CounterCubit(),
child: MaterialApp(
home: MyHomePage(),
),
);
}
}
- BlocBuilder We replaced the setState() logic with a BlocBuilder to automatically rebuild the UI when the state changes:
BlocBuilder<CounterCubit, int>(
builder: (context, count) {
return Text('$count');
},
)
- Increment Logic The increment button now directly interacts with the Cubit to update the state:
FloatingActionButton(
onPressed: () => context.read<CounterCubit>().increment(),
tooltip: 'Increment',
child: Icon(Icons.add),
)
This project is licensed under the MIT License. Feel free to use, modify, and distribute as needed.
For more details, check out the LICENSE file.
Contributions are always welcome! If you'd like to contribute, feel free to submit a pull request or open an issue.
- Email: tech.ramakanttiwari@gmail.com
- Medium: @tech.ramakant
- LinkedIn: @tech-ramakant
- YouTube: @Tech.Ramakant
Thank you for checking out the repository! 🎉