我们在上一章回中介绍了dio库中转换器相关的内容,本章回中将介绍网络综合示例:获取天气信息.闲话休提,让我们一起Talk Flutter吧。
我们在前面章回中介绍了网络操作相关的内容,本章回中将综合利用这些内容实现一个获取天气信息的例子。主要包含dio库的使用、网络操作的封装和JSON数据解析这些内容。在实际项目中这些内容是网络内容中必备的内容,而且它们之间需要相互配合才能完成网络操作。
///封装DIO网络库
///封装常用的网络参数
class HttpConfig {
static const String BASE_URL = "https://api.seniverse.com";
static const int TIME_OUT = 15;
///对应天气实况
// var TIAN_QI_SHI_KUANG = "https://api.seniverse.com/v3/weather/now.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c";
static const PATH_TIAN_QI_SHI_KUANG = "/v3/weather/now.json";
///对应24小时逐小时天气预报
// var HOUR24 = "https://api.seniverse.com/v3/weather/hourly.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c&start=0&hours=24";
static const PATH_HOUR24 = "/v3/weather/hourly.json";
///对应未来15天逐日天气预报和和昨日天气,不过免费的key只能获取3天的天气预报
// var FORECAST_DAYS = "https://api.seniverse.com/v3/weather/daily.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c&start=0&days=3";
static const PATH_FORECAST_DAYS = "/v3/weather/daily.json";
}
class HttpRequest {
static final baseOptions = BaseOptions(
baseUrl: HttpConfig.BASE_URL,
connectTimeout: Duration(seconds: HttpConfig.TIME_OUT),
sendTimeout: Duration(seconds: HttpConfig.TIME_OUT),
receiveTimeout: Duration(seconds: HttpConfig.TIME_OUT),
);
static final mdio = Dio(baseOptions);
///把网络操作相关的功能封装成独立的方法,网络操作相关的数据通过url和params参数传递
static Future<T> request<T>(String url,{
String method='get',
required Map<String,dynamic> params,
Interceptor? interceptor,
}) async {
final option = Options(method: method);
///添加拦截器
Interceptor _interceptor = InterceptorsWrapper(
onRequest: (options,handler) {
return handler.next(options);
},
onResponse: (response,handler){
print('response: ' + response.toString());
return handler.next(response);
},
onError: (error,handler) {
print('response: ' + error.toString());
return handler.next(error);
},
);
mdio.interceptors.add(_interceptor);
///默认也会抛出异常,这里只用来捕获特定的异常
try {
Response response = await mdio.request(
url, queryParameters: params, options: option);
return response.data;
}on DioException catch (e) {
print(e.toString());
return Future.error(e);
}
}
}
///获取天气信息,网络框架使用httpRequest,请求参数使用map添加
_getWeatherInfo() async {
var url = HttpConfig.BASE_URL+HttpConfig.PATH_TIAN_QI_SHI_KUANG;
Map<String,String> queryParams = {};
queryParams['key'] = PrivateKey.key;
queryParams['location'] = 'beijing';
queryParams['language'] = 'zh-Hans';
queryParams['unit'] = 'c';
TestRequest _testRequest = TestRequest();
_testRequest.addRequestParams('key',PrivateKey.key)
.addRequestParams('location', 'beijing')
.addRequestParams('language', 'zh-Hans')
.addRequestParams('unit', 'c');
HttpRequest.request(url, params: queryParams)
.then((value){
debugPrint(XZWeatherBeanEntity.fromJson(value).toString());
XZWeatherBeanEntity.fromJson(value).results?.forEach((element) {
print("now: ${element.now}");
});
});
}
///获取天气信息,网络框架使用httpRequest,请求参数使用map添加
_getWeatherInfo() async {
var url = HttpConfig.BASE_URL+HttpConfig.PATH_TIAN_QI_SHI_KUANG;
Map<String,String> queryParams = {};
queryParams['key'] = PrivateKey.key;
queryParams['location'] = 'beijing';
queryParams['language'] = 'zh-Hans';
queryParams['unit'] = 'c';
TestRequest _testRequest = TestRequest();
_testRequest.addRequestParams('key',PrivateKey.key)
.addRequestParams('location', 'beijing')
.addRequestParams('language', 'zh-Hans')
.addRequestParams('unit', 'c');
HttpRequest.request(url, params: queryParams)
.then((value){
debugPrint(XZWeatherBeanEntity.fromJson(value).toString());
XZWeatherBeanEntity.fromJson(value).results?.forEach((element) {
print("now: ${element.now}");
});
});
}
ElevatedButton(
onPressed: () {
debugPrint('get weather button clicked');
_getWeatherInfo();
},
child: Text('get weather by HttpRequest'),
),
上面的代码中没有包含JSON解析相关的代码,除此之外包含了全部的内容,没有包含的代码可以查看Github上完整内容。代码中的api来自心知天气的api操作手册,这里只列出了一部分。
编译并且运行上面的程序,可以获取到北京的实时天气信息。不过大家需要使用自己申请到的私钥替换代码中的PrivateKey.key
。
上面的示例代码中只演示了如何查询实时天气信息,建议大家自己动手实现查询最近3天天气信息的内容,这样可以起到举一反三的效果。
看官们,关于"网络综合示例:获取天气信息"相关的内容就介绍到这里,欢迎大家在评论区交流与讨论!