How to load async data on InitState method?

· 3 min read
load async data on InitState method
load async data on InitState method

Looking for a way to load async data on InitState Method?? You’ll need some data before the build method runs. Using GoogleAuth code, execute the build method till a stream runs… now read the below-given article and Load async data on InitState method.

Also, check this article for Decoding JSON in the flutter

How to load async data on InitState method?

Use StreamBuilder to do this. This will run the builder method whenever the data in stream changes.

Try the Below code snippet :

StreamBuilder<List<Content>> _getContentsList(BuildContext context) {
    final BlocProvider blocProvider = BlocProvider.of(context);
    int page = 1;
    return StreamBuilder<List<Content>>(
        stream: blocProvider.contentBloc.contents,
        initialData: [],
        builder: (context, snapshot) {
          if (snapshot.data.isNotEmpty) {
            return ListView.builder(itemBuilder: (context, index) {
              if (index < snapshot.data.length) {
                return ContentBox(content: snapshot.data.elementAt(index));
              } else if (index / 5 == page) {
                page++;
                blocProvider.contentBloc.index.add(index);
              }
            });
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        });
  }

Initially, it is an empty array and shows the CircularProgressIndicator. Once you make an API call the data fetched is added to the contents array, which will run the builder method. When the user scrolls down, more content is fetched and added to the contents array which will again run the builder method.

Another method would be to create an async method and call it from your initState( ) a method is shown below:

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

 void asyncMethod() async {
   await asyncCall1();
   await asyncCall2();
   // ....
 }

 

Conclusion:

In this article, we have learned How to load async data on InitState method?

Thank you for visiting the Article 🙂 Hope this has helped!!!
Keep Learning, Keep Fluttering !!!

Do let us know if you need any further assistance with Flutter Development.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter

Leave a Reply