rozerro
rozerro

Reputation: 7176

Why to use Future.delayed in initState()?

Why does this example use Future.delayed with no duration (actually a zero duration)?

void initState() {
    Future.delayed(
      Duration.zero,
      () {
        final Provider = Provider.of<ProductProvider>(context, listen: false);
        productProvider.loadValues(widget.product);
      },
    );
  

Upvotes: 2

Views: 2790

Answers (2)

Senay Gebre
Senay Gebre

Reputation: 11

The thing is that the code inside the Future.delayed will be executed after the widget build completes. We use this methodology to build the widget with some pre-loaded data while we send a request to get other data, once we get the data it will be updated. It is best practice for showing loading widgets after the layout frame built. What if we don't use the Future.delayed at all? There will be inconsistency within the page you are displaying. That means you are showing the loading widget before the build method renders the widget.

Explanation: Dart has two modes of code execution: "Asynchronous" code execution and Synchronous code execution. The event loop prioritizes Synchronous codes first, followed by Asynchronous codes. The build function in the Statefull widget is synchronous code that runs on the main isolate/thread, therefore the Asynchronous code Future.delayed will wait till the synchronous code "build()" method completes its duty. The code Future.delayed will then be performed on the main thread, but it will wait zero seconds; the Future class requires a time, and we simply give it 0 seconds.

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63649

initState() does not contain context and Duration.zero= Duration(seconds: 0);

initState calls when this object is inserted into the tree.

The Future.delayed(Duration.zero, () {}) approach is using the behavior of Dart's event queue to delay execution until the next event loop iteration, at which point it is safe to access context since the widget is guaranteed to be built.

You can also check this question.

You can read more about delayed-code-execution-in-flutter

Upvotes: 4

Related Questions