集成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>
post(dynamic url, { Map<String, String> headers, dynamic body, Encoding encoding }) → Future<Response>
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
来捕获错误 两种写法均可以,我的以为第二种语法思路更明确.网络