网络编程与数据存储技术
网络请求
1 | dio: ^2.2.2 |
Future
什么是Future
Future表示在接下来的某个时间的值或错误,借助Future我们可以在Flutter实现异步操作。
它类似于ES6中的Promise,提供then和catchError的链式调用;
1 | import 'dart:async'; |
Future的then
1 | Future<String> testFuture() { |
async await
1 | test() async { |
JSON解析和序列化
- 从服务端返回的json数据格式,Flutter需要对json格式的字符串转为Dart对象。
手动序列化数据,在模型中序列化JSON数据
1 | { |
1 | //使用 |
使用代码生成库序列化 JSON 数据
使用Dio请求返回数据不是Json字符串,而是Json对象
- 将responseType 设置为ResponseType.plain,默认使用json接收的。
1 | responseType: ResponseType.plain, |
1 | json_annotation: ^2.0.0 |
1 | import 'package:json_annotation/json_annotation.dart'; |
- 每次修改模型文件,都要重新运行 - flutter packages pub run build_runner build
1 | 使用 |
shared_preferences本地存储
- 简单的,异步的,持久化的key-value存储系统;
- 在Android上它是基于SharedPreferences的;
- 在iOS上它是基于NSUserDefaults的;
1 | shared_preferences: ^0.5.3 |