setStateAsync method

Future<SetStateAsyncStatus> setStateAsync([
  1. VoidCallback? fn
])

Batches multiple setState calls into a single operation within the current event loop.

This improves performance by executing multiple state updates in one setState call. Returns a Future with status(success/disposed). When providing fn, the status could also be error if exceptions occur.

Implementation

Future<SetStateAsyncStatus> setStateAsync([VoidCallback? fn]) {
  if (_completer == null) {
    _completer = Completer();
    // Future.microtask() is not suitable here cause it has own error handling logic.
    scheduleMicrotask(() {
      if (mounted) {
        setState(() {
          _completer!.complete(SetStateAsyncStatus.success);
          for (final task in _tasks) {
            task.completer.complete(_runCallback(task.fn));
          }
        });
      } else {
        _completer!.complete(SetStateAsyncStatus.disposed);
        for (final task in _tasks) {
          task.completer.complete(SetStateAsyncStatus.disposed);
        }
      }
      _tasks.clear();
      _completer = null;
    });
  }
  if (fn == null) {
    return _completer!.future;
  } else {
    final task = _Task(fn);
    _tasks.add(task);
    return task.completer.future;
  }
}