Home > Blockchain >  Why to use Future.delayed in initState()?
Why to use Future.delayed in initState()?

Time:11-14

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);
      },
    );
  

CodePudding user response:

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

  • Related