http
集成http库
1https://pub.dartlang.org/packages/http 2添加依赖 3dependencies: 4 http: ^0.12.0 5安装 6flutter packages get 7导入 8import '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); //处理响应数据
1}).catchError((error) { 2 print('$error错误'); 3});
返回值都用到Dart Futures, 类似JavaScript中的promise 官方推荐使用async/await来调用网络请求
1 void addProduct(Product product) async { 2 Map<String, dynamic> param = { 3 'title': product.title, 4 'description': product.description, 5 'price': product.price 6 }; 7 try { 8 final http.Response response = await http.post( 9 'https://flutter-cn.firebaseio.com/products.json', 10 body: json.encode(param), 11 encoding: Utf8Codec()); 12 13 final Map<String, dynamic> responseData = json.decode(response.body); 14 print('$responseData 数据'); 15 16 } catch (error) { 17 print('$error错误'); 18 } 19 }
用 try catch来捕获错误 两种写法都可以,个人觉得第二种语法思路更明确.