How to use Provider State Management In Flutter step by step

Using Provider for state management in Flutter is a popular choice due to its simplicity and flexibility. Here’s a step-by-step guide on how to use Provider for state management in your Flutter app:

Step 1: Add Dependencies

Ensure you have the necessary dependencies added to your pubspec.yaml file:

dependencies:
flutter:
sdk: flutter
provider: ^5.0.0

Then, run flutter pub get to fetch the dependencies.

Step 2: Create Your Model

Define the data model that you want to manage using Provider. This could be a simple class or a complex object depending on your app’s requirements.

Example:

class CounterModel extends ChangeNotifier {
int _count = 0;
int get count => _count;

void increment() {
_count++;
notifyListeners(); // Notify listeners of the change
}
}

Step 3: Wrap Your Widgets with Providers

Wrap the widgets that need access to the state with Provider widgets. You can use different types of providers like ChangeNotifierProvider, Provider, or StreamProvider depending on your needs.

Example:

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => CounterModel(),
child: MaterialApp(
title: 'Flutter Provider Example',
home: MyHomePage(),
),
);
}
}

Step 4: Access the State

You can access the state in your widgets using Provider.of<T>(context) or context.watch<T>() for listening to changes.

Example:

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counter = Provider.of<CounterModel>(context);

return Scaffold(
appBar: AppBar(
title: Text('Flutter Provider Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Count:',
),
Text(
'${counter.count}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => counter.increment(),
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Step 5: Update the State

To update the state, simply call the appropriate method on the model, and then call notifyListeners() to notify the listeners (widgets) about the change.

Step 6: Handle Disposal

If your model uses resources that need to be freed when no longer needed, override the dispose() method in your model class.

That’s it! You’ve successfully implemented state management using Provider in Flutter. This pattern provides a scalable and efficient way to manage state in your Flutter applications.

Also Read:- How to use GetX State management in Flutter

Flutter Lifecycle Methods: An In-Depth Exploration

Top 100 Flutter interview questions and answers in 2024

Leave a Comment

Your email address will not be published. Required fields are marked *