StateProvider Widget: Read Function

Learn about the StateProvider widget in Riverpod and how the read function works.

Reading the StateProvider

The following controller widget is the most important one, where we have used the Riverpod’s read() method to change the state of the provided objects.

Press + to interact
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../model/any_type_provider_model.dart';
void increment(BuildContext context) {
context.read(stateProviderInteger).state += 1;
}
void changeName(BuildContext context) {
context.read(stateProviderName).state = 'Json!';
}
void changeCity(BuildContext context) {
context.read(stateProviderCity).state = 'Jericho!';
}
void clearName(BuildContext context) {
context.read(stateProviderName).state = 'John';
}
void clearCity(BuildContext context) {
context.read(stateProviderCity).state = 'Chicago';
}
void changeLittleMonk(BuildContext context) {
context.read(stateProviderClass).state =
StateProviderModel('Now I am a big monk with white beard!', 70);
}
void reverseAgeOfLittleMonk(BuildContext context) {
context.read(stateProviderClass).state =
StateProviderModel('Now I am a little monk again!', 6);
}

We can notice that we have passed the BuildContext context inside each method, so the data flows through that context, and we can read the Provider state. The Provider state object is either integer, or string, or even a data class. However, in each case, the distinction is clear enough. Because our application logic is clear, it’s become easier for us to visualize what will happen.

In our application, we have pressed several buttons, however the Scaffold widget has not been rebuilt. You can track the ...

Get hands-on with 1400+ tech skills courses.