Intermediate
How do you manage state in a Flutter application?
State management in Flutter refers to the way we manage the state of our application to ensure a responsive user interface. Various approaches exist for state management, including Provider, Riverpod, and Bloc.
Here’s a simple step-by-step guide using the Provider package:
- Add Dependency: Include the Provider package in your pubspec.yaml file.
- Create a Model: Define a class that holds your app's state.
- Wrap Your App: Use the ChangeNotifierProvider to wrap your main app widget.
- Consume State: Use Consumer widget to access the state in your widgets.
Example code snippet:
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
// In main.dart:
void main() {
runApp(ChangeNotifierProvider(
create: (context) => Counter(),
child: MyApp(),
));
}