作者:一种姿态获得无可取代 | 来源:互联网 | 2023-08-21 18:07
我正在从服务器获取数据,并试图在网格视图中进行设置,但出现错误:
type 'Future>' is not a subtype of type 'List' in type cast
这是我的数据类:
class Data with ChangeNotifier {
Data({
this.name,this.image,});
final String image;
final String name;
factory Data.fromJson(Map json) {
print(json['title'].toString());
return Data(
name: json['title'].toString(),image: json['image'].toString(),);
}
}
这是我在Data_screen中调用的位置:
var datas= Provider.of(context).fetchData() as List;
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> fetchData() async {
var respOnse= await http.get(url);
var respOnseJson= json.decode(response.body);
print(responseJson);
return (responseJson['datas'])
.map((p) => Data.fromJson(p))
.toList();
}
消息非常清晰。您不能从List
投射到Future>
。尝试使用:
List fetchData() async {
var respOnse= await http.get(url);
var respOnseJson= json.decode(response.body);
print(responseJson);
return (responseJson['datas'])
.map((p) => Data.fromJson(p))
.toList();
}
或通过Future
返回新的List
Future> fetchData() async {
var respOnse= await http.get(url);
var respOnseJson= json.decode(response.body);
print(responseJson);
var respOnse= (responseJson['datas'])
.map((p) => Data.fromJson(p))
.toList();
return Future.value(response)
}
这只是一个主意(未经测试)