[英]type 'Future<dynamic>' is not a subtype of type 'List<Application>?'
[英]type 'Future<List<Data>>' is not a subtype of type 'List<Data>' in type cast
我正在從服務器獲取數據並嘗試將其設置在網格視圖中,但出現錯誤:
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();
}
信息如此清晰。 您不能從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();
}
或者用List<Data>
返回一個新的Future
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)
}
這只是一個想法(未經測試)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.