ITPub博客

首页 > IT职业 > IT职场 > Flutter 网络请求库http

Flutter 网络请求库http

IT职场 作者:wghdd 时间:2021-09-09 09:59:46 0 删除 编辑

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 headers }) → Future
  • (必须)url:请求地址
  • (可选)headers:请求头
post(dynamic url, { Map headers, dynamic body, Encoding encoding }) → Future
  • (必须)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 responseData = json.decode(response.body);
     //处理响应数据
     
    }).catchError((error) {
      print('$error错误');
    });

返回值都用到Dart Futures, 类似JavaScript中的promise
官方推荐使用async/await来调用网络请求

  void addProduct(Product product) async {
    Map 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 responseData = json.decode(response.body);
      print('$responseData 数据');
      
    } catch (error) {
      print('$error错误');
    }
  }

用 try catch来捕获错误
两种写法都可以,个人觉得第二种语法思路更明确.

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1775/viewspace-2814796/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 集合的工具类
请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    109
  • 访问量
    863