- 颤振教程
- 颤动 - 主页
- 颤振 - 简介
- 颤振 - 安装
- 在 Android Studio 中创建简单的应用程序
- Flutter - 架构应用
- Dart 编程简介
- Flutter - Widget 简介
- Flutter - 布局简介
- Flutter - 手势简介
- Flutter - 状态管理
- 颤动 - 动画
- Flutter - 编写 Android 特定代码
- Flutter - 编写 IOS 特定代码
- Flutter - 包简介
- Flutter - 访问 REST API
- Flutter - 数据库概念
- Flutter - 国际化
- 颤振 - 测试
- Flutter - 部署
- Flutter - 开发工具
- Flutter - 编写高级应用程序
- 颤动 - 结论
- 颤动有用的资源
- Flutter - 快速指南
- Flutter - 有用的资源
- Flutter - 讨论
Flutter - 访问 REST API
Flutter提供了http包来消耗HTTP资源。http 是一个基于 Future 的库,并使用等待和异步功能。它提供了许多高级方法并简化了基于 REST 的移动应用程序的开发。
基本概念
http 包提供了一个高级类和 http 来执行 Web 请求。
http 类提供执行所有类型 HTTP 请求的功能。
http 方法接受 url 以及通过 Dart Map 的附加信息(发布数据、附加标头等)。它请求服务器并以异步/等待模式收集响应。例如,下面的代码从指定的url读取数据并在控制台中打印。
print(await http.read('https://flutter.dev/'));
一些核心方法如下 -
read - 通过 GET 方法请求指定的 url 并以 Future<String> 形式返回响应
get - 通过 GET 方法请求指定的 url,并以 Future<Response> 形式返回响应。Response 是保存响应信息的类。
post - 通过发布提供的数据,通过 POST 方法请求指定的 url,并将响应返回为 Future<Response>
put - 通过 PUT 方法请求指定的 url 并返回响应作为 Future <Response>
head - 通过 HEAD 方法请求指定的 url 并以 Future<Response> 返回响应
delete - 通过 DELETE 方法请求指定的 url 并以 Future<Response> 返回响应
http还提供了一个更标准的HTTP客户端类,client。客户端支持持久连接。当向特定服务器发出大量请求时,它将很有用。需要使用 close 方法正确关闭它。否则,它与http类类似。示例代码如下 -
var client = new http.Client();
try {
print(await client.get('https://flutter.dev/'));
}
finally {
client.close();
}
访问产品服务API
让我们创建一个简单的应用程序来从 Web 服务器获取产品数据,然后使用ListView显示产品。
在 Android studio 中创建一个新的Flutter应用程序, product_rest_app。
将默认启动代码 (main.dart) 替换为我们的Product_nav_app代码。
将资产文件夹从product_nav_app复制到product_rest_app,并在pubspec.yaml文件中添加资产。
flutter:
assets:
- assets/appimages/floppy.png
- assets/appimages/iphone.png
- assets/appimages/laptop.png
- assets/appimages/pendrive.png
- assets/appimages/pixel.png
- assets/appimages/tablet.png
在 pubspec.yaml 文件中配置 http 包,如下所示 -
dependencies: http: ^0.12.0+2
在这里,我们将使用最新版本的http包。Android studio 将发送 pubspec.yaml 已更新的包警报。
单击获取依赖项选项。Android studio 将从互联网获取包并为应用程序正确配置它。
在 main.dart 文件中导入 http 包 -
import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http;
创建一个新的 JSON 文件 products.json,其中包含产品信息,如下所示 -
[
{
"name": "iPhone",
"description": "iPhone is the stylist phone ever",
"price": 1000,
"image": "iphone.png"
},
{
"name": "Pixel",
"description": "Pixel is the most feature phone ever",
"price": 800,
"image": "pixel.png"
},
{
"name": "Laptop",
"description": "Laptop is most productive development tool",
"price": 2000,
"image": "laptop.png"
},
{
"name": "Tablet",
"description": "Tablet is the most useful device ever for meeting",
"price": 1500,
"image": "tablet.png"
},
{
"name": "Pendrive",
"description": "Pendrive is useful storage medium",
"price": 100,
"image": "pendrive.png"
},
{
"name": "Floppy Drive",
"description": "Floppy drive is useful rescue storage medium",
"price": 20,
"image": "floppy.png"
}
]
创建一个新文件夹 JSONWebServer 并放置 JSON 文件 products.json。
运行任何以 JSONWebServer 作为根目录的 Web 服务器并获取其 Web 路径。例如,http://192.168.184.1:8000/products.json。我们可以使用任何网络服务器,如 apache、nginx 等,
最简单的方法是安装基于节点的 http 服务器应用程序。按照下面给出的步骤安装并运行 http-server 应用程序
安装 Nodejs 应用程序 ( nodejs.org )
转到 JSONWebServer 文件夹。
cd /path/to/JSONWebServer
使用 npm 安装 http-server 包。
npm install -g http-server
现在,运行服务器。
http-server . -p 8000 Starting up http-server, serving . Available on: http://192.168.99.1:8000 http://127.0.0.1:8000 Hit CTRL-C to stop the server
在 lib 文件夹中创建一个新文件 Product.dart 并将 Product 类移入其中。
在Product类中编写一个工厂构造函数Product.fromMap,将映射数据Map转换为Product对象。通常,JSON 文件会被转换为 Dart Map 对象,然后转换为相关对象(Product)。
factory Product.fromJson(Map<String, dynamic> data) {
return Product(
data['name'],
data['description'],
data['price'],
data['image'],
);
}
Product.dart 的完整代码如下 -
class Product {
final String name;
final String description;
final int price;
final String image;
Product(this.name, this.description, this.price, this.image);
factory Product.fromMap(Map<String, dynamic> json) {
return Product(
json['name'],
json['description'],
json['price'],
json['image'],
);
}
}
在主类中编写两个方法 - parseProducts 和 fetchProducts - 从 Web 服务器获取产品信息并将其加载到 List<Product> 对象中。
List<Product> parseProducts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) =>Product.fromJson(json)).toList();
}
Future<List<Product>> fetchProducts() async {
final response = await http.get('http://192.168.1.2:8000/products.json');
if (response.statusCode == 200) {
return parseProducts(response.body);
} else {
throw Exception('Unable to fetch products from the REST API');
}
}
请注意以下几点 -
Future用于延迟加载产品信息。延迟加载是一个将代码的执行推迟到需要时才执行的概念。
http.get 用于从 Internet 获取数据。
json.decode 用于将 JSON 数据解码为 Dart Map 对象。JSON 数据解码后,将使用 Product 类的 fromMap 将其转换为 List<Product>。
在 MyApp 类中,添加新的成员变量、Future<Product> 类型的 products 并将其包含在构造函数中。
class MyApp extends StatelessWidget {
final Future<List<Product>> products;
MyApp({Key key, this.products}) : super(key: key);
...
在 MyHomePage 类中,添加 Future<Product> 类型的新成员变量 products 并将其包含在构造函数中。另外,删除 items 变量及其相关方法 getProducts 方法调用。将 products 变量放置在构造函数中。当应用程序首次启动时,它将只允许从互联网获取产品一次。
class MyHomePage extends StatelessWidget {
final String title;
final Future<ListList<Product>> products;
MyHomePage({Key key, this.title, this.products}) : super(key: key);
...
更改 MyApp 小部件的构建方法中的主页选项 (MyHomePage) 以适应上述更改 -
home: MyHomePage(title: 'Product Navigation demo home page', products: products),
更改 main 函数以包含 Future<Product> 参数 -
void main() => runApp(MyApp(fetchProduct()));
创建一个新的小部件 ProductBoxList 以在主页中构建产品列表。
class ProductBoxList extends StatelessWidget {
final List<Product> items;
ProductBoxList({Key key, this.items});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
child: ProductBox(item: items[index]),
onTap: () {
Navigator.push(
context, MaterialPageRoute(
builder: (context) =gt; ProductPage(item: items[index]),
),
);
},
);
},
);
}
}
请注意,我们使用导航应用程序中使用的相同概念来列出产品,只不过它是通过传递 List<Product> 类型的产品(对象)设计为单独的小部件。
最后,修改MyHomePage小部件的构建方法,以使用 Future 选项而不是正常的方法调用来获取产品信息。
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: Center(
child: FutureBuilder<List<Product>>(
future: products, builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData ? ProductBoxList(items: snapshot.data)
// return the ListView widget :
Center(child: CircularProgressIndicator());
},
),
)
);
}
这里请注意,我们使用 FutureBuilder 小部件来渲染小部件。FutureBuilder 将尝试从其 future 属性(类型为 Future<List<Product>>)中获取数据。如果 future 属性返回数据,它将使用 ProductBoxList 渲染小部件,否则抛出错误。
main.dart的完整代码如下 -
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'Product.dart';
void main() => runApp(MyApp(products: fetchProducts()));
List<Product> parseProducts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => Product.fromMap(json)).toList();
}
Future<List<Product>> fetchProducts() async {
final response = await http.get('http://192.168.1.2:8000/products.json');
if (response.statusCode == 200) {
return parseProducts(response.body);
} else {
throw Exception('Unable to fetch products from the REST API');
}
}
class MyApp extends StatelessWidget {
final Future<List<Product>> products;
MyApp({Key key, this.products}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Product Navigation demo home page', products: products),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
final Future<List<Product>> products;
MyHomePage({Key key, this.title, this.products}) : super(key: key);
// final items = Product.getProducts();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: Center(
child: FutureBuilder<List<Product>>(
future: products, builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData ? ProductBoxList(items: snapshot.data)
// return the ListView widget :
Center(child: CircularProgressIndicator());
},
),
)
);
}
}
class ProductBoxList extends StatelessWidget {
final List<Product> items;
ProductBoxList({Key key, this.items});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
child: ProductBox(item: items[index]),
onTap: () {
Navigator.push(
context, MaterialPageRoute(
builder: (context) => ProductPage(item: items[index]),
),
);
},
);
},
);
}
}
class ProductPage extends StatelessWidget {
ProductPage({Key key, this.item}) : super(key: key);
final Product item;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(this.item.name),),
body: Center(
child: Container(
padding: EdgeInsets.all(0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Image.asset("assets/appimages/" + this.item.image),
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.name, style:
TextStyle(fontWeight: FontWeight.bold)),
Text(this.item.description),
Text("Price: " + this.item.price.toString()),
RatingBox(),
],
)
)
)
]
),
),
),
);
}
}
class RatingBox extends StatefulWidget {
@override
_RatingBoxState createState() =>_RatingBoxState();
}
class _RatingBoxState extends State<RatingBox> {
int _rating = 0;
void _setRatingAsOne() {
setState(() {
_rating = 1;
});
}
void _setRatingAsTwo() {
setState(() {
_rating = 2;
});
}
void _setRatingAsThree() {
setState(() {
_rating = 3;
});
}
Widget build(BuildContext context) {
double _size = 20;
print(_rating);
return Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (
_rating >= 1
? Icon(Icons.star, ize: _size,)
: Icon(Icons.star_border, size: _size,)
),
color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size,
),
),
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (
_rating >= 2
? Icon(Icons.star, size: _size,)
: Icon(Icons.star_border, size: _size, )
),
color: Colors.red[500],
onPressed: _setRatingAsTwo,
iconSize: _size,
),
),
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (
_rating >= 3 ?
Icon(Icons.star, size: _size,)
: Icon(Icons.star_border, size: _size,)
),
color: Colors.red[500],
onPressed: _setRatingAsThree,
iconSize: _size,
),
),
],
);
}
}
class ProductBox extends StatelessWidget {
ProductBox({Key key, this.item}) : super(key: key);
final Product item;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2), height: 140,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Image.asset("assets/appimages/" + this.item.image),
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.name, style:TextStyle(fontWeight: FontWeight.bold)),
Text(this.item.description),
Text("Price: " + this.item.price.toString()),
RatingBox(),
],
)
)
)
]
),
)
);
}
}
最后运行应用程序查看结果。它与我们的导航示例相同,只是数据来自互联网,而不是在编码应用程序时输入的本地静态数据。