Home > Enterprise >  why does this function Future.delay make 2 print in flutter?
why does this function Future.delay make 2 print in flutter?

Time:08-09

I have a code like these

Future.delayed(Duration(seconds: 5),(){
     print("5 seconds");
   });

in

import 'package:flutter/material.dart';
class Loading extends StatefulWidget {
  const Loading({Key? key}) : super(key: key);
  @override
  State<Loading> createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
  int counter=0;
  @override
  Widget build(BuildContext context) {
   Future.delayed(Duration(seconds: 5),(){
     print("5 seconds");
   });
    return Scaffold(
      appBar: AppBar(
        title: Text("Loading"),
        centerTitle: true,
      ),
      body:TextButton(
        onPressed: () {
          setState((){
            counter  ;
          });
        },
        child: Text("Counter is $counter"),
      ),
    );
  }
  void getstart(){
    Future.delayed(Duration(seconds: 3),(){
         print("3 seconds");
    }
    );
  }
  @override
  void initState() {
    getstart();
    print("this is innit State");
  }
  @override
  void dispose() {
    print("this is dispose");
  }
}

when I ran Asynchronous Code it print 2 "5 second" in build widget, I dont know why it happens

CodePudding user response:

The widget's build method gets called in a lot of cases in Flutter. This answer goes over a few of them.

When the build method is called all the code in it is run, including your Future.delayed method with a 5 second wait.

In your case the build method will be run once whenever you build the widget, and again whenever you increment the counter, or when any of the parent widget's state changes.

In general the build method of a widget should only contain code used to render the UI and should not contain any other code since that code will be run more than once, and will slow down the frame rate of your app.

CodePudding user response:

  it happens because when it build first time it print first time 
  after 5 second when future.delay is over it will print again 
  
  do not use future.delay in build 

CodePudding user response:

You can't expect that build is only called a single time. If something changes the state of the widget or any of its ancestors build might possibily be called more than once

  • Related