【发布时间】:2019-05-06 04:31:55
【问题描述】:
我尝试从 api 获取数据:https://location-query.herokuapp.com/location?key_word=ha%20noi
这是响应 json:
{
"code":200,
"key_word":"ha noi",
"result":[
{
"id":1581130,
"name":"Ha Noi",
"country":"VN",
"coord":{
"lon":105.841171,
"lat":21.0245
}
}
]
}
这是我的数据类:
class Coord {
final double lon, lat;
Coord({this.lon, this.lat});
factory Coord.fromJson(Map<String, dynamic> json) {
return Coord(
lon: json['lon'],
lat: json['lat']
);
}
}
class Location {
final int id;
final String name, country;
final Coord coord;
Location({this.id, this.name, this.country, this.coord});
factory Location.fromJson(Map<String, dynamic> json) {
return Location(
id: json['id'],
name: json['name'],
country: json['country'],
coord: Coord.fromJson(json['coord'])
);
}
}
class Locations {
final int code;
final String key_word;
final List<Location> result;
Locations({this.code, this.key_word, this.result});
factory Locations.fromJson(Map<String, dynamic> json) {
return Locations(
code: json['code'],
key_word: json['key_word'],
result: json['result'].map((value) => Location.fromJson(value)).toList()
);
}
}
这是我的请求类:
class SearchLocation {
Future<Locations> search(key_word) async {
final get = await http.get(Api().searchLocation(key_word));
if (get.statusCode == 200)
return Locations.fromJson(json.decode(get.body));
else
throw Exception('Can not request');
}
}
这是读取数据的代码,但是snapshot.hasData总是返回false:
SearchLocation searchLocation = SearchLocation();
_searchResult = searchLocation.search(_controller.text);
FutureBuilder<Locations>(
future: _searchResult,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text('Done');
}
else {
print('Location: No Result');
return Text('No result');
}
})
【问题讨论】:
-
你确定没有抛出异常吗?
snapshot.hasError的值是多少? -
我有一个关于 snapshot.hasError 的异常,但我不知道如何显示日志错误
-
你检查了官方文档中的所有
AsyncSnapshot属性吗? -
现在就阅读吧……