Flutter 網絡請求庫http

http

集成http庫json

https://pub.dartlang.org/packages/http
添加依賴
dependencies:
  http: ^0.12.0
安裝
flutter packages get
導入
import 'package:http/http.dart' as http;

經常使用方法

get(dynamic url, { Map<String, String> headers }) → Future<Response>
  • (必須)url:請求地址
  • (可選)headers:請求頭
post(dynamic url, { Map<String, String> headers, dynamic body, Encoding encoding }) → Future<Response>
  • (必須)url:請求地址
  • (可選)headers:請求頭
  • (可選)body:參數
  • (編碼)Encoding:編碼 例子
http.post('https://flutter-cn.firebaseio.com/products.json',
            body: json.encode(param),encoding: Utf8Codec())
    .then((http.Response response) {
      final Map<String, dynamic> responseData = json.decode(response.body);
     //處理響應數據
     
    }).catchError((error) {
      print('$error錯誤');
    });

返回值都用到Dart Futures, 相似JavaScript中的promise 官方推薦使用async/await來調用網絡請求promise

  void addProduct(Product product) async {
    Map<String, dynamic> param = {
      'title': product.title,
      'description': product.description,
      'price': product.price
    };
    try {
      final http.Response response = await http.post(
          'https://flutter-cn.firebaseio.com/products.json',
          body: json.encode(param),
          encoding: Utf8Codec());

      final Map<String, dynamic> responseData = json.decode(response.body);
      print('$responseData 數據');
      
    } catch (error) {
      print('$error錯誤');
    }
  }

用 try catch來捕獲錯誤 兩種寫法均可以,我的以爲第二種語法思路更明確.網絡

相關文章
相關標籤/搜索