Flutter- How to load async data on InitState method (2023)

In flutter app development, We need to show data when the screen opens, but sometimes this data comes from API or local database so takes some time to load that's why flutter gives us async and wait keywords which means The async computation cannot provide a result immediately when it is started because the program may need to wait for an external response like Reading a file, Querying a database and Fetching data from an API, etc. Basically, our approach is to put async code put inside the initState() method but flutter doesn't allow it. So I am sharing in this article How to load async data on the InitState method.

Error:

You can see an error in the below snapshot.

======== Exception caught by widgets library =======================================================
The following assertion was thrown building Builder:
_ErrorgramState.initState() returned a Future.

State.initState() must be a void method without an `async` keyword.

Rather than awaiting on asynchronous work directly inside of initState, call a separate method to do this work without awaiting it.

 

Cause of Error:

Flutter directly doesn't allow async keywords inside the initState(). Because async returns future type data but initState() required only return void type of data.

Solution for load async data on InitState method:

Method 1:

 @override
  void initState() {
    loadData().then((int value) {
      print("printData-->" + value.toString());
    });
   super.initState();
  }

Future<int> loadData() async {
    return Future(() => 10);
  }

 

Method 2:

  @override
  void initState() {
    Future.delayed(Duration.zero, () async {
      int data = await loadData();
      print("printData-->" + data.toString());
    });
    super.initState();
  }

Future<int> loadData() async {
    return Future(() => 10);
  }

 

Method 3:

  WidgetsBinding.instance.addPostFrameCallback((_) async {
      int data = await loadData();
      print("printData-->" + data.toString());
    });


  Future<int> loadData() async {
    return Future(() => 10);
  }

 

Full Code:

import 'package:flutter/material.dart';

class Errorgram extends StatefulWidget {
  const Errorgram({Key? key}) : super(key: key);

  @override
  State<Errorgram> createState() => _ErrorgramState();
}

class _ErrorgramState extends State<Errorgram> {
  @override
  void initState() {
    loadData().then((int value) {
      print("printData-->" + value.toString());
    });
    Future.delayed(Duration.zero, () async {
      int data = await loadData();
      print("printData-->" + data.toString());
    });

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      int data = await loadData();
      print("printData-->" + data.toString());
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        bottom: false,
        child: Scaffold(
            appBar: AppBar(
              title: Text("Errorgram"),
            ),
            body: Center(
              child: Text(""),
            )));
  }

  Future<int> loadData() async {
    return Future(() => 10);
  }
}

 

Output:

I/flutter (16368): printData-->10
I/flutter (16368): printData-->10
I/flutter (16368): printData-->10

 

Conclusion:

We saw various methods for How to load async data on InitState method step by step in detail. I hope this post may help you.

 

Tags: