Flutter 网络请求库http
生活随笔
收集整理的這篇文章主要介紹了
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來捕獲錯誤 兩種寫法都可以,個人覺得第二種語法思路更明確.
?
?
轉載于:https://www.cnblogs.com/zhujiabin/p/10333253.html
總結
以上是生活随笔為你收集整理的Flutter 网络请求库http的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 陶瓷锅的正确开锅方法
- 下一篇: 碧梧图是谁画的呢?