与其说是Flutter的网络请求,倒不如说是Dart的网络请求。实际上这块是对系列八第5点的一个复习,我们直接看代码:
在.yaml文件中添加http依赖,然后执行Packages get
dependencies: flutter:
sdk: flutter
http: ^0.12.0+2
新建一个api.dart文件
as httpclass ServerApi
static FutureString getArticle async
var url
_doGeturl
static FutureString _doGetString url async
http.Response response await http.geturl
response.body
就是对Future、async以及await关键字的使用,这块系列八已经介绍过
应用了我们刚刚添加依赖的http库
在main.dart文件中添加如下代码,我们就直接使用一个刚新建的Flutter工程:
void setState
// This call to setState tells the Flutter framework that something has
// changed this State, causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState, the build method would not be
// called again, and so nothing would appear to happen.
// _counter++
ServerApi.getArticle.thenjson
print
改变一下FAB的点击响应,在这里发起网络请求,这里直接打印返回的json,如果在实际项目中可以对json进行解析成实体类对象然后使用。打印结果如下:
还没有评论,来说两句吧...