Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter provider in initState

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();
  }
}
like image 812
user6097845 Avatar asked Aug 19 '19 15:08

user6097845


People also ask

Can provider be used inside the initstate function?

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?

What are stateful widgets in flutter?

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.

What is initstate() method in stateful widgets?

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.

Why we are creating a counter app in flutter?

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.


1 Answers

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

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

  void someMethod() {
    // TODO: do something
  }
}
like image 156
Rémi Rousselet Avatar answered Sep 18 '22 12:09

Rémi Rousselet