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. 

@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();
}

OR:

@override
void initState() {
  getData();  //call async function.
  super.initState();
}

getData() async{
    //your 'await' code goes here
}

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

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

1 Commet on this Article

yaakoub

The Error was gone but the function inside initeState will not excute !! 

1 year ago


Please Wait...