瞎扯
写app离不开网络请求,没有网络请求没有灵魂
不多bb
HttpClient
import 'dart:io';
var httpClient = new HttpClient();
getData() async {
var httpClient = new HttpClient();
var uri = new Uri.http(
'example.com', '/path1/path2', {'param1': '42', 'param2': 'foo'});
var request = await httpClient.getUrl(uri);
var response = await request.close();
var responseBody = await response.transform(UTF8.decoder).join();
}
上面是官方的例子.
请求来说很简单.
但是有两个东西是新的.
async
await
async
很简单,异步的意思.相当于new了一个线程
await
这个呢,可以理解为携程
也就是等待这一行走完返回结果的意思.
所以在这个方法里面,每一步都是很直观的写出来的,不用担心异步回调的问题.
是不是很简单呢.
_getIPAddress() async {
var url = 'https://httpbin.org/ip';// 请求地址
var httpClient = new HttpClient();
String result;
try { //可能出错
var request = await httpClient.getUrl(Uri.parse(url));//发起请求
var response = await request.close();//关闭流,得到结果
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(UTF8.decoder).join();//转换为json
var data = JSON.decode(json);//json解析
result = data['origin']; //得到对象
} else {
result =
'Error getting IP address:\nHttp status ${response.statusCode}'; //接口出错
}
} catch (exception) {
result = 'Failed getting IP address';//产生异常
}
// If the widget was removed from the tree while the message was in flight,
// we want to discard the reply rather than calling setState to update our
// non-existent appearance.
if (!mounted) return;//生命周期控制
setState(() { //更新UI
_ipAddress = result;
});
}
交流群:493180098,这是个很少吹水,交流学习的群.
APP开发维护咨询群 : 492685472 ,承接APP迭代.开发维护.咨询业务,付费快速解决问题.
网友评论