How to call setState in flutter

242

I don't think there is much of a difference other than;

Number 1 is the official endorsed way of showing what you want to perform a state change for. Number 2 is how we newbies like to do it :)

Read up on in here,

https://api.flutter.dev/flutter/widgets/State/setState.html

Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.

Meaning that it does not matter if if is on the inside or not. everything is rebuild with your newly set variables.

Generally it is recommended that the setState method only be used to wrap the actual changes to the state, not any computation that might be associated with the change.

setState() is not able to handle future events it seems, they need to be awaited and finished before you can apply them in a setstate.

https://flutter.dev/docs/perf/rendering/best-practices

When setState() is called on a State, all descendent widgets rebuild. Therefore, localize the setState() call to the part of the subtree whose UI actually needs to change. Avoid calling setState() high up in the tree if the change is contained to a small part of the tree.

Share:
242
BambinoUA
Author by

BambinoUA

Expirienced in: Dart/Flutter WinDev/WebDev/WinDev Mobile PHP Clarion for Windows Microsoft C#

Updated on December 29, 2022

Comments

  • BambinoUA
    BambinoUA over 1 year

    Is this any essential difference how to call setState method using below code samples?

    1. Setting state variable inside setState

    setState((){
      _stateVariable1 = 'value1';
      _stateVariable2 = 'value2';
    });
    

    2. Setting state variable outside setState

    _stateVariable1 = 'value1';
    _stateVariable2 = 'value2';
    setState((){});