Google News
logo
Flutter - Interview Questions
What is the purpose of the "setState" method in Flutter?
In Flutter, `setState()` is a method that is used to update the state of a widget and trigger a rebuild of the widget tree. When you call `setState()`, Flutter schedules a rebuild of the widget tree, and when the rebuild happens, the widget's `build()` method is called again with the updated state.

`setState()` is important in Flutter because it allows you to update the user interface in response to user interactions, data changes, or other events. For example, you might use `setState()` to update the text of a button when the user clicks it, or to change the color of a widget based on some data that was fetched from a server.

Here is an example of how `setState()` can be used to update the state of a widget :
class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

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

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter')),
      body: Center(
        child: Text('$_counter'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        child: Icon(Icons.add),
      ),
    );
  }
}

In this example, `_counter` is a variable that holds the current value of the counter. The `_incrementCounter()` method is called when the user taps the floating action button, and it calls `setState()` to update the `_counter` variable and trigger a rebuild of the widget. The `build()` method returns a `Text` widget that displays the current value of `_counter`, and a `FloatingActionButton` that calls `_incrementCounter()` when pressed.

Advertisement