flutteruser-interfacechangenotifier

Flutter multiple notifyListeners calls


I use notifyListeners from ChangeNotifier in flutter. What happens if I call notifyListeners() three times in a row? How many times will the UI be updated in this case?

notifyListeners сall code:

class Data with ChangeNotifier
{
  String _data = 'some text';
  String get getData => _data;
  void changeString(String newString)
  {
    _data = newString;
    notifyListeners();
    notifyListeners();
    notifyListeners();
  }
}

The usage:

class MyTextField extends StatelessWidget {
  const MyTextField({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return TextField(
      onChanged: (newData) => context.read<Data>().changeString(newData),
    );
  }
}

Widget tree (if it's important):

MyTextField is child of Widget2.

Widget2 is child of Widget1.

Widget1 is child of HomePage.

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Container(child: Text(context.watch<Data>().getData),),
      ),
      body: Center(
        child: Widget1(),
      )
    );
  }
}

Solution

  • The UI will only update once. You can test this by simply printing something inside the build method when the notifyListeners() is called 3 times or more. The reason the UI is not updated even though notify is called 3 times is because of flutter. Flutter only updates the widget tree if the data in the tree is different from the new data coming in. So even though notifyListeners() is called 1000 times, if the current widget tree is the same as before notify was called, flutter doesn't update the UI.