网络库
介绍
用于发送HTTP请求的可组合的、基于future的库。
包含一组高级函数和类,可以方便地使用HTTP资源。它是多平台的,支持移动、桌面和浏览器。
依赖库引入
dependencies:
flutter:
# 3.网络访问库
http: 0.13.3
封装
一种思路基本步骤
- 库 import
- 核心方法
- 转码为 utf8
- 异常抛出
封装就是在使用时传入 成功、失败、完成的回调
另一种思路是使用 Future 的特性,完成后回调链
- then()、catchError()、whenComplete()
import 'package:http/http.dart' as http;
class HttpManager {
static Utf8Decoder utf8decoder = Utf8Decoder();
static void getData(String url,
{Map<String, String> headers, Function success, Function fail, Function complete}) async {
try {
var response = await http.get(Uri.parse(url), headers: headers);
if (response.statusCode == 200) {
// 解析 json 字符串,返回 Map<String,dynamic> 类型
var result = json.decode(utf8decoder.convert(response.bodyBytes));
success(result);
} else {
throw Exception('"Request failed with status: ${response.statusCode}"');
}
} catch (e) {
fail(e);
} finally {
if (complete != null) {
complete();
}
}
}
static Future requestData(String url, {Map<String, String> headers}) async {
try {
var response = await http.get(Uri.parse(url), headers: headers);
if (response.statusCode == 200) {
var result = json.decode(utf8decoder.convert(response.bodyBytes));
return result;
} else {
throw Exception('"Request failed with status: ${response.statusCode}"');
}
}catch(e){
Future.error(e);
}
}
}
使用
// 下拉刷新
void refresh() {
HttpManager.getData(
getUrl(),
success: (json) {
M model = getModel(json);
removeUselessData(model.itemList);
getData(model.itemList);
viewState = ViewState.done;
// 下一页数据的处理
nextPageUrl = getNextUrl(model);
refreshController.refreshCompleted();
refreshController.footerMode.value = LoadStatus.canLoading;
// 额外的操作:例如加载home的数据列表
doExtraAfterRefresh();
},
fail: (e) {
JinToast.showError(e.toString());
refreshController.refreshFailed();
viewState = ViewState.error;
},
complete: () => notifyListeners(),
);
}
// 下拉刷新
void refresh() {
HttpManager.getData(
getUrl(),
success: (json) {
M model = getModel(json);
removeUselessData(model.itemList);
getData(model.itemList);
viewState = ViewState.done;
// 下一页数据的处理
nextPageUrl = getNextUrl(model);
refreshController.refreshCompleted();
refreshController.footerMode.value = LoadStatus.canLoading;
// 额外的操作:例如加载home的数据列表
doExtraAfterRefresh();
},
fail: (e) {
JinToast.showError(e.toString());
refreshController.refreshFailed();
viewState = ViewState.error;
},
complete: () => notifyListeners(),
);
}