How to run Async ’await’ Code in initState() in Flutter App

In this example, we are going to show the way to run or call asynchronous functions, codes inside initState() in Flutter Apps.  Sometimes, you may need to execute async code while initializing app. But Flutter will show an error if you add 'async' modifier to initState. See the example below to solve this issue. 

To Run Async 'await' codes, function inside initState():

@override
void initState() {
  //you are not allowed to add async modifier to initState
  Future.delayed(Duration.zero,() async {
        //your async 'await' codes goes here
  });
  super.initState();
}

See the Full Flutter Example Below:

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget{
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    //you are not allowed to add async modifier to initState
    Future.delayed(Duration.zero,() async {
         String var1 = await testfunction();
         //here is the async code, you can execute any async code here
         print(var1);
    });
    
    super.initState();
  }
  
  //this is async test function
  Future<String> testfunction(){
    print("This is test function");
    return Future(()=>"abc"); 
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: Scaffold(
        appBar: AppBar(title:Text("Async Function in initState()")),
        body: Container( 
          child: Center(
            child: Center( 
              child: Text("initState => async"),
            ),  
          ),
        )
      )
    );
  }
}

Console Output:

In this way, you can execute async 'await' codes inside initState() in Flutter App.

No any Comments on this Article


Please Wait...