类型强制类型'Future <List <Data >>'不是类型'List <Data>'的子类型

时间:2019-12-03 04:53:31

标签: android ios flutter dart

我正在从服务器获取数据,并试图在网格视图中进行设置,但出现错误:

type 'Future<List<Data>>' is not a subtype of type 'List<Data>' in type cast

这是我的数据类:

class Data with ChangeNotifier {
Data({
  this.name,
  this.image,
});

final String image;
final String name;


factory Data.fromJson(Map<String, dynamic> json) {
print(json['title'].toString());
return Data(
  name: json['title'].toString(),
  image: json['image'].toString(),
 );

}
}

这是我在Data_screen中调用的位置:

 var datas= Provider.of<Datas>(context).fetchData() as List<Data>;
 var datalength = datas.length;

小部件:

 Expanded(
            child: GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(

                crossAxisSpacing: 10,
                mainAxisSpacing: 10,
              ),
              padding: EdgeInsets.only(left: 28, right: 28, bottom: 58),
              itemCount: datas.length,

              itemBuilder: (context, index) => DataCard(
                datas[index],
                index: index,
                onPress: () {
                },
              ),
            ),
          ),

在Datas.dart中:

 Future<List<Data>> fetchData() async {
 var response = await http.get(url);
 var responseJson = json.decode(response.body);
 print(responseJson);
 return (responseJson['datas'])
    .map<Data>((p) => Data.fromJson(p))
  .toList();

}

1 个答案:

答案 0 :(得分:2)

消息非常清晰。您不能从List<Data>投射到Future<List<Data>>。尝试使用:

List<Data> fetchData() async {
 var response = await http.get(url);
 var responseJson = json.decode(response.body);
 print(responseJson);
 return (responseJson['datas'])
    .map<Data>((p) => Data.fromJson(p))
  .toList();
}

或通过Future返回新的List<Data>

Future<List<Data>> fetchData() async {
 var response = await http.get(url);
 var responseJson = json.decode(response.body);
 print(responseJson);
 var response = (responseJson['datas'])
    .map<Data>((p) => Data.fromJson(p))
  .toList();
 return Future.value(response)
}

这只是一个主意(未经测试)