Flutter和Dart系列九:簡單的網絡請求

與其說是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進行解析成實體類對象然後使用。打印結果如下:

        

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章