[英]flutter error with futurebuilder and http json
您好,我正在使用 flutter 開發應用程序,但 Futurebuilder 出現錯誤,我不明白請幫忙
我試圖根據 id 與未來的 builder 獲取 title 和 desc
這是我的 json
{"title":"15%GANT","desc":"donne 15 % sur les gants"}
這是我的未來
Future<Data> fetchData(int id, String type) async {
var queryParameters = {
'type': type,
'id': id,
};
String url = 'tartapain.bzh';
var uri = Uri.https(url, '/api/scan/get.php', queryParameters);
final response = await http.get(uri);
if (response.statusCode == 200) {
if (response.body != null) {
return Data.fromJson(json.decode(response.body));
}
} else {
throw Exception('Failed to load the post');
}
}
這是我的數據 class
class Data {
final String title;
final String desc;
Data({
this.title,
this.desc,
});
factory Data.fromJson(Map<String, dynamic> json) {
print(json['desc'] + " " + json['title'] + "\n");
return Data(
desc: json['desc'],
title: json['title'],
);
}
}
這是 mt 初始化
Future<Data> futureData;
@override
void initState() {
super.initState();
futureData = fetchData(widget.id, 'get_info_id');
}
這是我的futureBuilder
FutureBuilder(
future: futureData,
initialData: [],
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: Text("Loading..."));
}
if (snapshot.hasData) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
snapshot.data.title,
style: TextStyle(color: Colors.white, fontSize: 18),
),
Text(
snapshot.data.desc,
style: TextStyle(color: Colors.white, fontSize: 12),
)
],
);
} else if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.white, fontSize: 12),
);
} else {
return CircularProgressIndicator(
valueColor:
new AlwaysStoppedAnimation<Color>(Colors.black));
}
})
我得到這個錯誤:
“int”類型不是“Iterable”類型的子類型
似乎錯誤是由應為 String 類型的 ID 引起的。 這解決了這個問題。
我建議在您的 model 中進行一些檢查,以防這些值為空。
class Data {
final String title;
final String desc;
Data({
this.title,
this.desc,
});
factory Data.fromJson(Map<String, dynamic> json) {
//print(json['desc'] + " " + json['title'] + "\n");
return Data(
desc: (json['desc']!=null)?json['desc']:'no desc',
title: (json['title']!=null)?json['title']:'no title',
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.