为了账号安全,请及时绑定邮箱和手机立即绑定

【备战春招】第12天 Flutter中的网络编程

标签:
Android

课程名称Flutter从入门到进阶 实战携程网App 一网打尽核心技术
课程章节:Flutter进阶提升:网络编程与数据存储技术
课程讲师CrazyCodeBoy

课程内容

http中的 get、post 请求

http库是Flutter中自带的网络请求相关的操作类,网络请求通过 HttpClient实现,类中包括了get、post、put、delete、patch、head 等网络请求方式。

通过 http 库实现 get 请求:

Future<http.Response> fetchGet() {
  return http.get('https://jsonplaceholder.typicode.com/posts/1');
}

通过 http 库实现 post 请求:

Future<http.Response> fetchPost() {
  return http.post('https://jsonplaceholder.typicode.com/posts/1');
}

请求响应内容转化为 Dart 对象

get 请求和 post 请求都会返回一个包含了 http.Response的 Future。直接使用 http.Response不方便,可以将 http.Response转换为 Dart 对象,大致经过以下几个步骤:

  • 使用dart:convert package将响应内容转化为一个json Map;
  • 使用fromJson()工厂函数,将json Map 转化为一个CommonModel对象;
    示例代码:
Future<CommonModel> fetchPost() async {
    final response = await http.get('https://www.devio.org/io/flutter_app/json/test_common_model.json');
    final result = json.decode(response.body);
    return new CommonModel.fromJson(result);
  }

完整的 CommonModel 对象:

class CommonModel {
  final String icon;
  final String title;
  final String url;
  final String statusBarColor;
  final bool hideAppBar;

  CommonModel({this.icon, this.title, this.url, this.statusBarColor, this.hideAppBar});

  factory CommonModel.fromJson(Map<String, dynamic> json) {
    return CommonModel(
      icon: json['icon'],
      title: json['title'],
      url: json['url'],
      statusBarColor: json['statusBarColor'],
      hideAppBar: json['hideAppBar'],
    );
  }
}

课程总结

本节介绍了http库发起的 get、post 请求,并将请求相应 http.Response 转化为 Dart 对象。在实际开发中还会用到 dio。

dio 是开源的强大 http 请求库,支持 Restful API、FormData、拦截器、请求取消、Cookie 管理、文件上传/下载、超时等处理。
图片描述

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
11
获赞与收藏
16

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消