Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setState() vs notifyListeners(), which one is more efficient?

Tags:

flutter

dart

I always aim to make my widgets Stateless instead Stateful for performance benefits. In some cases(updating the BottomNavigationBar index e.g.) notifyListeners() can provide identical functionality of the setState().

At first, I think notifyListener() is lower level, more fundemantal function comparing to setState(), so it should be more efficient. Because setState() method may triggers too many higher level framework methods, so it may spends more CPU power.

But it's hard to be sure without making a proper and detailed performance testing. So what is the answer?

Edit: Also, in some cases, notifyListeners() behaves exactly like setState(). For example, I have Text widget inside a StatelessWidget that holds a Random value and when I notify the an unrelated value inside the Class, the Text widget is also getting update. So, what is the difference?

like image 346
Esen Mehmet Avatar asked Jul 08 '19 09:07

Esen Mehmet


People also ask

What does notifyListeners do?

notifyListeners method Null safety Call this method whenever the object changes, to notify any clients the object may have changed. Listeners that are added during this iteration will not be visited. Listeners that are removed during this iteration will not be visited after they are removed.

What is setState in flutter?

setState method Null safetyNotify the framework that the internal state of this object has changed. Whenever you change the internal state of a State object, make the change in a function that you pass to setState: setState(() { _myState = newValue; }); The provided callback is immediately called synchronously.


1 Answers

Assuming that you're comparing ChangeNotifier.notifyListener with State.setState to rebuild the widget tree, then:

setState will always win.

The reason, notifyListener rebuilds your widget tree because it causes setState itself.

For notifyListener to work, there's usually a StatefulWidget somewhere in your tree that does the following:

class MyState extends State<T> {
  ChangeNotifier notifier;

  initState() {
    notifier.addListener(() => setState(() {}));
  }
}

In any case, this probably doesn't matter.

like image 97
Rémi Rousselet Avatar answered Oct 06 '22 10:10

Rémi Rousselet