I'm currently trying Provider as a state management solution, and I understand that it can't be used inside the initState function.
All examples that I've seen call a method inside a derived ChangeNotifier
class upon user action (user clicks a button, for example), but what if I need to call a method when initialising my state?
Motivation: Creating a screen which loads assets (async) and shows progress
An example for the ChangeNotifier
class (can't call add
from initState
):
import 'package:flutter/foundation.dart';
class ProgressData extends ChangeNotifier {
double _progress = 0;
double get progress => _progress;
void add(double dProgress) {
_progress += dProgress;
notifyListeners();
}
}
I'm currently trying Provider as a state management solution, and I understand that it can't be used inside the initState function. All examples that I've seen call a method inside a derived ChangeNotifier class upon user action (user clicks a button, for example), but what if I need to call a method when initialising my state?
There are two types of widgets provided in Flutter. As the name suggests Stateful Widgets are made up of some ‘States’. The initState () is a method that is called when an object for your stateful widget is created and inserted inside the widget tree.
It is basically the entry point for the Stateful Widgets. initState () method is called only and only once and is used generally for initializing the previously defined variables of the stateful widget. initState () method is overridden mostly because as mentioned earlier it is called only once in its lifetime.
We are creating a simple counter app in flutter, which will help us in understanding state management in flutter application and deciding which is a better way to build our app and complete the project.
You can call such methods from the constructor of your ChangeNotifier
:
class MyNotifier with ChangeNotifier {
MyNotifier() {
someMethod();
}
void someMethod() {
// TODO: do something
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With