Search⌘ K
AI Features

Application of StateNotifierProvider

Explore the practical application of StateNotifierProvider in Flutter using the Riverpod library. Understand how to manage both simple and complex states, organize your code for maintainability, and minimize widget rebuilds for efficient app performance.

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

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:

Dart
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 of the nature of the state here (it ...