Flutter Provider: Listen to Variable Change
In Flutter, the provider package is a popular choice for state management. It allows you to create a data model and share it across multiple widgets, ensuring that any changes to the model are automatically reflected in the UI. To listen to variable changes using provider, you need to follow these steps:
- Create a Model Class: First, you’ll need to create a model class that holds the variables you want to listen to. For example, let’s say we want to listen to changes to a count variable:
class CounterModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
- Wrap Widgets with a ChangeNotifierProvider: Wrap your main widget or the widget tree that needs to listen to variable changes with a
ChangeNotifierProvider
. Pass an instance of the model class as the provider’svalue
:
ChangeNotifierProvider<CounterModel>(
create: (context) => CounterModel(),
child: MyApp(),
)
- Access the Provider: To access the provider and listen to variable changes in any widget within the provider’s scope, use the
Provider.of<CounterModel>(context)
. You can listen to changes using theConsumer
widget or by directly using the provider:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counterModel = Provider.of<CounterModel>(context, listen: true);
return Scaffold(
appBar: AppBar(
title: Text('Example App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Count:',
),
Consumer<CounterModel>(
builder: (context, counterModel, _) {
return Text(
'${counterModel.count}',
style: TextStyle(fontSize: 24),
);
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => counterModel.increment(),
child: Icon(Icons.add),
),
);
}
}
Here, we’re using the Consumer
widget to listen to changes explicitly. Whenever the count
variable changes in the CounterModel
, the UI automatically updates thanks to the state management provided by the provider package.
If you want to directly access the provider in a widget, you can use the Provider.of<CounterModel>(context, listen: false)
. However, keep in mind that if you use this approach, you’ll need to manage the widget’s state manually by calling setState()
when necessary.
That’s it! You now have a model class that notifies listeners when a variable changes, and the UI is updated accordingly using the provider package in Flutter.