1. 程式人生 > 遊戲攻略 >《怪物獵人崛起》2.0版斬斧配裝思路講解

《怪物獵人崛起》2.0版斬斧配裝思路講解

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

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

轉載於:https://my.oschina.net/roycehe/blog/2223359