我正在使用其中一個 openweathermap 來根據城市名稱獲取緯度和經度。 每當用戶輸入無效的城市名稱時,這就是來自 api 的回應。
我怎樣才能捕捉到這一點并向用戶顯示錯誤訊息。
這是進行 api 呼叫的函式。
Constants myConstaints = Constants();
Future<CityInfo> gettingCityData(String cityName) async {
var url = Uri.parse(
'https://api.openweathermap.org/geo/1.0/direct?q=$cityName&limit=1&appid=${myConstaints.apiKey}');
var response = await http.get(url);
if (response.statusCode == 200) {
var i = CityInfo.fromJson(jsonDecode(response.body));
return i;
} else
throw Exception('error');
}
CityInfo 類及其建構式
class CityInfo {
String name;
double lat;
double long;
CityInfo.fromJson(List<dynamic> json)
: name = json[0]['name'],
lat = json[0]['lat'].toDouble(),
long = json[0]['lon'].toDouble();
}
提供者
Future<void> cityName(String cityName) async {
cityInfo = await gettingCityData(cityName);
notifyListeners();
}
uj5u.com熱心網友回復:
API 正在回傳城市串列。它可能會回傳一個空串列。
首先, CityInfo.fromJson 不應將串列作為輸入。它應該只專注于將 CityInfo JSON 物件轉換為 CityInfo 物件。
class CityInfo {
String name;
double lat;
double long;
CityInfo.fromJson(Map<String, dynamic> json)
: name = json['name'],
lat = json['lat'].toDouble(),
long = json['lon'].toDouble();
}
現在,請注意 CityInfo 如何可以為空,因此您的未來應該回傳一個可為空的 CityInfo
Future<CityInfo?> gettingCityData(String cityName)
現在處理請求,
Future<CityInfo?> gettingCityData(String cityName) async {
final url = Uri.parse(
'https://api.openweathermap.org/geo/1.0/direct?q=$cityName&limit=1&appid=${myConstaints.apiKey}');
final response = await http.get(url);
if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(response.body);
if (data.isEmpty) return null; // List is empty.
final cityJson = data.first as Map<String, dynamic>;
return CityInfo.fromJson(cityJson);
} else
throw Exception('Error');
}
}
現在,該方法可以稱為,
Future<void> cityName(String cityName) async {
cityInfo = await gettingCityData(cityName);
if (cityInfo == null) {
// City was not found. Show some message here.
}
notifyListeners();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529626.html
標籤:扑镖例外打开天气图
上一篇:PythonThreadPoolExecutor:如何評估導致超時的原因
下一篇:如何禁用特定例外的警告?
