Flutter和Dart系列九:简单的网络请求

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xlh1191860939/article/details/96018608

与其说是Flutter的网络请求,倒不如说是Dart的网络请求。实际上这块是对系列八第5点的一个复习,我们直接看代码:

  1. 在.yaml文件中添加http依赖,然后执行Packages get

    dependencies:
      flutter:
        sdk: flutter
      http: ^0.12.0+2
    
  2. 新建一个api.dart文件

    import 'package:http/http.dart' as http;
    
    class ServerApi {
      static Future<String> getArticle() async {
        var url = "https://interface.meiriyiwen.com/article/today?dev=1";
        return _doGet(url);
      }
    
      static Future<String> _doGet(String url) async {
        http.Response response = await http.get(url);
        return response.body;
      }
    }
    
    • 就是对Future、async以及await关键字的使用,这块系列八已经介绍过
    • 应用了我们刚刚添加依赖的http库
  3. 在main.dart文件中添加如下代码,我们就直接使用一个刚新建的Flutter工程:

    void _incrementCounter() {
        setState(() {
          // This call to setState tells the Flutter framework that something has
          // changed in this State, which causes it to rerun the build method below
          // so that the display can reflect the updated values. If we changed
          // _counter without calling setState(), then the build method would not be
          // called again, and so nothing would appear to happen.
    //      _counter++;
          ServerApi.getArticle().then((json) {
            print("json: $json");
          });
        });
      }
    

    改变一下FAB的点击响应,在这里发起网络请求,这里直接打印返回的json,如果在实际项目中可以对json进行解析成实体类对象然后使用。打印结果如下:

        

展开阅读全文

没有更多推荐了,返回首页