Home > Software engineering >  How can i have multiple function to fetch data in a FutureBuilder
How can i have multiple function to fetch data in a FutureBuilder

Time:02-16

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.

CodePudding user response:

Please try the code below:

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

@override
  void initState() {
    _future = sendData()();
    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;
          
});
  • Related