Normal Dev
Normal Dev

Reputation: 13

How can i have multiple function to fetch data in a FutureBuilder

In a FutureBuilder i'm trying to use multiple methods with different types, all of them fetch data from the api, the main problem that i'm having is that all of the functions have different types, so i'm having problem on putting methods because of their types.

Upvotes: 1

Views: 187

Answers (1)

chuanpham
chuanpham

Reputation: 469

Please try the code below:

Future? _future;
Future<dynamic> getData() async {
  //you can have more functions here, for explanation purpose, i'll have 2
  final data1 = await getData1();
  final data2 = await getData2();
  return [data1, data2];
}

@override
  void initState() {
    _future = getData()();
    super.initState();
  }

///

FutureBuilder(
        future: _future,
        builder: (context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return CupertinoActivityIndicator();
          }

          if (snapshot.hasError) {
            return SomethingWentWrong();
          }
          final data1= snapshot.data[0] as YourData1Model;
          final data2 = snapshot.data[1] as YourData2Model;
          
});

Upvotes: 4

Related Questions