Flutter 网络请求get与post的两个库
第一种:http库
https://pub.dev/packages/http
添加依赖
dependencies:http: ^0.12.0
安装http
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>(必须)url:请求地址
例子
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...
点击查看剩余70%
网友评论0