flutter基础总结1
1、如何执行异步任务(async task).
假设我们有个http请求,当然很耗时,就需要用异步执行此任务。
Future<dynamic>? getWeatherDataByCity(Map<String, dynamic> params) async {
http.Response response = await http.get(Uri.http(baseWeatherUrl, '/data/2.5/weather',
params));
print(response.statusCode);
if (response.statusCode == 200) {
print(response.body);
var json = jsonDecode(response.body);
return json;
}
}
}
注意,在dart中执行异步任务,需要使用 await 和 async 关键词。
await 用于修饰调用方法, async则在调用方法名后添加。
2、关于 Futures 的一些用法
对于await 返回的对象,我们一般用 Future包裹一下。拿到后,既可以直接使用。例如:
var weatherData = await getCityWeather(typedName);
上面http接口,返回的是一个json对象,json对象返回类型 Future, 这是一个可用json对象。假设返回body的json串是:
{
"coord":{
"lon":114.2667,"lat":30.5833},
"weather":[{
"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}]
}
获取json字段就很容易:
var main = weatherData['weather'] ['main'];
3、在Dart 怎么用 http package.
其实 dart 已经提供了开源的 http 包给大家使用。就在这里:
【HTTP】dart 的 http 库
具体用法其实上面讲异步时已经展示过了:
final String baseWeatherUrl = "api.openweathermap.org";
Map<String, dynamic> params = HashMap<String, String>();
params["lat"]= '$lat';
params["lon"]= '$lon';
params[