Flutter 網絡請求庫http


http

集成http庫

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來調用網絡請求

  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來捕獲錯誤 兩種寫法都可以,個人覺得第二種語法思路更明確.

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM