Application of StateNotifierProvider

Continue to learn about StateNotifier and StateNotifierProvider and how you can use them in a Flutter application.

Meaning of StateNotifierProvider

If we break the word StateNotifierProvider into three parts, what do we find? We will find three meaningful words: State, Notifier, and Provider.

As we know, the state is a built-in characteristic or property of an object, like a person has a name, height, weight, etc. A notifier needs to notify a widget to a change of state. However, while notifying, it must provide them.

Let us consider an app like in the following image:

Thinking
A Flutter app that uses StateNotifierProvider and tracks widget rebuilds

On the left-hand side, we can see the app. On the right-hand side, we can track the widget rebuilds. Even though the app looks very simple, the structure is not that simple. Because we want to reduce widget rebuilds, we break the code into separate modules to make them loosely coupled.

Type of state required

Granted, the nature of the state is not always straightforward. But for this example, we have kept both simple and complex options.

A simple data model class that extends StateNotifier looks like this:

Press + to interact
import 'package:flutter_riverpod/flutter_riverpod.dart';
class NameNotifier extends StateNotifier<String> {
NameNotifier() : super('StateNotifier');
void addNames(String names) {
state = names;
}
void updateNames(String names) {
state = names;
}
}
final nameNotifierProvider =
StateNotifierProvider<NameNotifier, dynamic>((ref) {
return NameNotifier();
});

In addition to the simplicity ...

Get hands-on with 1400+ tech skills courses.