Flutter List<dynamic> is not a subtype of type FutureOr<List<Donation>>

Viewed 1168

I'm getting the error: type 'List<dynamic>' is not a subtype of type 'FutureOr<List<Donation>>'. I've checked the data type but but cant seem to find the cause of the error.

//getting the data from api call

Future<List<Donation>> _getDonationRecord() async {
   var res = await CallApi().donationRecords();
   var body = json.decode(res.body);
   return body.map((p) => Donation.fromJson(p)).toList();
}

//Building the futurebuilder

FutureBuilder<List<Donation>>(
   future: _getDonationRecord(),
   builder: (context, snapshot) {
      if (snapshot.hasData) {
        List<Donation> data = snapshot.data;
        return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return ListTile(
            leading: Icon(Icons.thumb_up,color: kPrimaryColor,) ,
            title: Text(data[index].hospital,style: TextStyle(color: Colors.black),),
            subtitle: Text(data[index].date,style: TextStyle(color: Colors.black),),
            trailing: Text(data[index].donorDonatedLitre,style: TextStyle(color: Colors.black),),
          );
        });
      } else if (snapshot.hasError) {
        return Text("${snapshot.error}");
      }
      return Center(child: CircularProgressIndicator());
    },
)
1 Answers

The problem is that json.decode returns dynamic. As a result, this type propagates to the end of a function and that's why you have such a type error. Try something like this:

Future<List<Donation>> _getDonationRecord() async {
   var res = await CallApi().donationRecords();
   var body = json.decode(res.body) as List<Object>;
   return body.map((p) => Donation.fromJson(p)).toList();
}

Or even like that:

var body = json.decode(res.body) as List<Map<String, Object>>;

Working with dynamic type is difficult for many reasons. A good idea to avoid it as much as possible. You can set up Dart analysis to have a compiling error in cases like that. You can read how to accomplish this here.

Related