Flutter provider listen to variable change

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:

  1. 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();
}
}

  1. 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’s value:


ChangeNotifierProvider<CounterModel>(
create: (context) => CounterModel(),
child: MyApp(),
)

  1. 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 the Consumer 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.

Leave a comment