当前位置: 首页 > 知识库问答 >
问题:

Flutter List不是类型FutureOR的子类型。

子车海
2023-03-14

我得到一个错误:输入'List'

//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个答案

吕高寒
2023-03-14

问题在于json。解码返回动态。因此,这种类型会传播到函数的末尾,这就是为什么会出现这种类型错误的原因。试着这样做:

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();
}

甚至像这样:

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

由于许多原因,使用动态类型很困难。一个尽可能避免的好主意。您可以将Dart分析设置为在类似情况下出现编译错误。您可以在这里阅读如何实现这一点。

 类似资料: