与其说是Flutter的网络请求,倒不如说是Dart的网络请求。实际上这块是对系列八第5点的一个复习,我们直接看代码:
在.yaml文件中添加http依赖,然后执行Packages get
1
2
3
4
5
6 1dependencies:
2 flutter:
3 sdk: flutter
4 http: ^0.12.0+2
5
6
新建一个api.dart文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 1import 'package:http/http.dart' as http;
2
3class ServerApi {
4 static Future<String> getArticle() async {
5 var url = "https://interface.meiriyiwen.com/article/today?dev=1";
6 return _doGet(url);
7 }
8
9 static Future<String> _doGet(String url) async {
10 http.Response response = await http.get(url);
11 return response.body;
12 }
13}
14
15
-
就是对Future、async以及await关键字的使用,这块系列八已经介绍过
- 应用了我们刚刚添加依赖的http库
-
在main.dart文件中添加如下代码,我们就直接使用一个刚新建的Flutter工程:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 1void _incrementCounter() {
2 setState(() {
3 // This call to setState tells the Flutter framework that something has
4 // changed in this State, which causes it to rerun the build method below
5 // so that the display can reflect the updated values. If we changed
6 // _counter without calling setState(), then the build method would not be
7 // called again, and so nothing would appear to happen.
8// _counter++;
9 ServerApi.getArticle().then((json) {
10 print("json: $json");
11 });
12 });
13 }
14
15
改变一下FAB的点击响应,在这里发起网络请求,这里直接打印返回的json,如果在实际项目中可以对json进行解析成实体类对象然后使用。打印结果如下: