Joe Sutter
Joe Sutter

Reputation: 17

Flutter Future.delayed on endless loop

I'm running this code

Future.delayed(Duration(milliseconds: 500)).then((value) => {opened = false,setState(() {}), value = "null"});
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    getStorage();
    Future.delayed(Duration(milliseconds: 500))
        .then((value) => {opened = false, setState(() {}), value = "null"});
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Container(
          color: Colors.green,
          alignment: Alignment.center,
          child: AnimatedContainer(
            duration: Duration(milliseconds: 3000),
            height: opened ? 0 : 300,
            width: opened ? 0 : 300,
            curve: Curves.fastOutSlowIn,
            alignment: Alignment.center,
            child: Lottie.asset('assets/101349-swing.json'),
          ),
        ),
      ),
    );
  }
}

and it returns

I/flutter (22251): false

continually and I want to avoid because I think it is inefficient.

Upvotes: 1

Views: 1640

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

You are adding Future.delay inside the build method and this is a StatefullWidget, build method can calls multitple time, like whenever you call setState() build method will trigger and recall the Future.delay which provide infinite loop in your case.

To call single time, override initState, you can do something like this,

  @override
  void initState() {
    super.initState();
    _initFuture();
  }

  _initFuture() async {
    Future.delayed(Duration(milliseconds: 500))
        .then((value) => {opened = false, setState(() {}), value = "null"});
  }

Upvotes: 3

Related Questions