Flutter provider in initState

user6097845 picture user6097845 · Aug 19, 2019 · Viewed 8.8k times · Source

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();
  }
}

Answer

Rémi Rousselet picture Rémi Rousselet · Aug 19, 2019

You can call such methods from the constructor of your ChangeNotifier:

class MyNotifier with ChangeNotifier {
  MyNotifier() {
    someMethod();
  }

  void someMethod() {
    // TODO: do something
  }
}