karina
karina

Reputation: 757

Why mutating variable directly will rebuild widget?

please run this widget:

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

class _MyWidgetState extends State<MyWidget> {
    bool aBoolean = false;
  @override
  Widget build(BuildContext context) {
    print('aBoolean will change over press button: $aBoolean');
    return RaisedButton(
        onPressed: () {
            aBoolean = !aBoolean;
        },
        child: const Text("Press Me"),
    );
  }
}

variable aBoolean will change on each press button.. is that mean mutating variable directly will rebuild widget..? so what setState({}) is for..? should I mutate variable directly or use setState..?

Upvotes: 1

Views: 412

Answers (2)

mirkancal
mirkancal

Reputation: 5365

If you just change the state directly without calling setState, the framework might not schedule a build and the user interface for this subtree might not be updated to reflect the new state.

source: setState method

It might rebuild without calling setState but as the documentation suggest, it might not work in the next scenario. It's better to mutate state with setState method

Upvotes: 2

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277507

Widgets do not rebuild unless you call setState (with a few exceptions).

As such calling setState is not optional.

Upvotes: 0

Related Questions