网络请求是开发APP必不可少的一部分,比如获取用户订单数据,获取商品列表,提交表单等等都离不了网络请求,那么在Flutter中如何进行网络请求呢?
Flutter官方推荐我们在Flutter中用Http进行网络请求。
Http是Flutter社区开发的一个可组合的、跨平台的用于Flutter的网络请求插件。
在pubspec.yaml中引入http插件;
调用http.get发送请求;
dependencies:
http: <latest_version>
Future<http.Response> fetchPost() {
return http.get('<https://jsonplaceholder.typicode.com/posts/1>');
}
http.get()返回一个包含http.Response的Future:
http.Response:类包含一个成功的HTTP请求接收到的数据;虽然发出网络请求很简单,但如果要使用原始的Future<http.Response>并不简单。为了让我们可以开开心心的写代码,我们可以将http.Response转换成我们自己的Dart对象。
创建一个CommonModel类
首先,我们需要创建一个CommonModel类,它包含我们网络请求的数据。它还将包括一个工厂构造函数,它允许我们可以通过json创建一个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'],
);
}
}