A5, AEHS, Lahore, Pakistan
+92 306 77 57 681
Introduction
State management is a crucial aspect of any Flutter application, as it determines how your app responds to user interactions and updates the UI. In this blog, we will discuss different state management approaches in Flutter and share best practices to help you maintain a clean and efficient codebase.
class Counter extends StatefulWidget {
@override
_CounterState createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Count: $_count'),
ElevatedButton(
onPressed: _increment,
child: Text('Increment'),
),
],
);
}
}class MyInheritedWidget extends InheritedWidget {
final int data;
MyInheritedWidget({
Key? key,
required this.data,
required Widget child,
}) : super(key: key, child: child);
@override
bool updateShouldNotify(covariant MyInheritedWidget oldWidget) {
return oldWidget.data != data;
}
static MyInheritedWidget? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
}
}
class CounterProvider with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
// Usage in a widget
final counterProvider = Provider.of<CounterProvider>(context);
Copy code
final counterProvider = StateProvider<int>((ref) => 0);
// Usage in a widget
final count = useProvider(counterProvider).state;
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
}
// Usage in a widget
final counterCubit = context.read<CounterCubit>();
setState for local, ephemeral state and move to more complex solutions like Provider or Bloc for app-wide state.BuildContext to access and manage state effectively within the widget tree.