Flutter State Management With Provider

Flutter State Management With Provider

ยท

2 min read

In this tutorial, I'll walk you through the basics of Provider. We'll build a simple app to "Follow" and "Unfollow" a list of users.

download.png

First thing first, What is "Provider" ?

Provider is a state management solution in Flutter. It's one of the first state management solutions recommended by the Flutter team and one of the simplest.

Why is state management important?

It centralizes all the states of various UI components and helps to handle data flow across the application.

Add The Package

Open your pubspec.yaml file, scroll down to dependencies, and add the Provider package (Check pub.dev for the latest version).

dependencies:
   provider: ^6.0.1
   . . .

Set up a model

Create a new file called user_provider.dart (or your preferred name choice). This is where the "business logic" will stay.

This class will extend ChangeNotifier. But first, what is this "ChangeNotifier" you might be wondering. According to flutter.dev:

ChangeNotifier is a simple class included in the Flutter SDK that provides change notification to its listeners. In other words, if something is a ChangeNotifier, you can subscribe to its changes. (It is a form of Observable, for those familiar with the term.)

Add the following code snippet:

import 'package:flutter/material.dart';

class UserProvider extends ChangeNotifier {
  final List<String> _usersList = [];
  List<String> get usersList => _usersList;

  follow(String user) {
    _usersList.add(user);
     // This call tells the widgets that are listening to this model to rebuild.
    notifyListeners();
  }

  unFollow(String user) {
    _usersList.removeWhere((element) => element == user);
     // This call tells the widgets that are listening to this model to rebuild.
    notifyListeners();
  }
}

Bind the model with the UI using ChangeNotifierProvider

ChangeNotifierProvider is the widget that initially creates an instance of the model we created above and provides it to whatever widget below the "Widget tree" that requires consuming it. This widget (ChangeNotifierProvider) comes from the provider package.

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => UserProvider(),
      child: const MyApp(),
    ),
  );
}

Consume the model

The Consumer widget (also from the Provider package), helps in "consuming" a model. Basically, any widget needing data from the model should be wrapped in a Consumer widget. However, We must specify the type of model we want to "consume". In this case, we want to consume the UserProvider model, so we write Consumer<UserProvider>.

Put everything together

Here's the full source code

Conclusion

Hopefully, by now you understand the basics of Provider for managing states in a Flutter app. Happy coding! ๐Ÿ™‚

ย