setState method

  1. @protected
void setState(
  1. VoidCallback fn
)

Notify the framework that the internal state of this object has changed.

Whenever you change the internal state of a State object, make the change in a function that you pass to setState:

setState(() { _myState = newValue; });

The provided callback is immediately called synchronously. It must not return a future (the callback cannot be async), since then it would be unclear when the state was actually being set.

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.

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.

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. For example, here a value used by the build function is incremented, and then the change is written to disk, but only the increment is wrapped in the setState:

Future<void> _incrementCounter() async {
  setState(() {
    _counter++;
  });
  Directory directory = await getApplicationDocumentsDirectory();
  final String dirName = directory.path;
  await File('$dir/counter.txt').writeAsString('$_counter');
}

It is an error to call this method after the framework calls dispose. You can determine whether it is legal to call this method by checking whether the mounted property is true.

Implementation

@protected
void setState(VoidCallback fn) {
  assert(_debugLifecycleState != _StateLifecycle.defunct);
  Object? result = fn() as dynamic;
  assert(
    result is! Future,
    'setState() callback argument returned a Future.\n\n'
    'Instead of performing asynchronous work inside a call to setState(), first '
    'execute the work (without updating the component state), and then synchronously '
    'update the state inside a call to setState().',
  );
  _element!.markNeedsBuild();
}