Sobes.tech
Junior — Middle

When data is changed in a child widget, which functional mechanism notifies its state of this change?

sobes.tech AI

Answer from AI

In Flutter, the mechanism used to notify the widget about data changes is setState().

When the data that the widget's state depends on changes, the setState() method is called, which informs the framework that the state has changed and the widget needs to be rebuilt.

Example:

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  int counter = 0;

  void increment() {
    setState(() {
      counter++; // data change
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text('Counter: $counter');
  }
}

Thus, setState() is a functional mechanism that notifies Flutter of the need to update the UI when the state changes.