网络请求基础
在现代应用程序中,网络请求是一个不可或缺的功能。Flutter 提供了多种库来处理 HTTP 请求,其中最常用的是 http 库。
安装 http 库
首先,在项目的 pubspec.yaml 文件中添加对 http 库的依赖:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3然后运行 flutter pub get 来安装这个库。
发送 GET 请求
发送 GET 请求是获取数据的一种常见方式。以下是如何使用 http 库发送 GET 请求:
// www.javascriptcn.com code example
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
if (response.statusCode == 200) {
// 请求成功,解析 JSON 数据
var data = jsonDecode(response.body);
print(data);
} else {
// 请求失败
throw Exception('Failed to load data');
}
}发送 POST 请求
POST 请求用于向服务器提交数据。以下是如何使用 http 库发送 POST 请求:
// www.javascriptcn.com code example
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> postData() async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': 'foo',
'body': 'bar',
'userId': '1',
}),
);
if (response.statusCode == 201) {
// 请求成功,解析 JSON 数据
var data = jsonDecode(response.body);
print(data);
} else {
// 请求失败
throw Exception('Failed to post data');
}
}处理异步操作
在网络请求中,处理异步操作是非常重要的。Dart 提供了 async 和 await 关键字来简化异步代码的编写。
使用 FutureBuilder
在 Flutter 中,可以使用 FutureBuilder 小部件来显示从网络请求中获取的数据。以下是一个简单的示例:
// www.javascriptcn.com code example
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('网络请求示例')),
body: FutureBuilder<Todo>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
);
}
}
class Todo {
final int userId;
final int id;
final String title;
Todo({this.userId, this.id, this.title});
factory Todo.fromJson(Map<String, dynamic> json) {
return Todo(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
Future<Todo> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
if (response.statusCode == 200) {
// 请求成功,解析 JSON 数据
return Todo.fromJson(jsonDecode(response.body));
} else {
// 请求失败
throw Exception('Failed to load data');
}
}错误处理
在进行网络请求时,错误处理是必不可少的。应该考虑各种可能的错误情况,并提供相应的用户反馈。
捕获和处理异常
在发送请求时,可能会遇到各种异常。可以通过捕获这些异常并提供适当的反馈来增强用户体验。
// www.javascriptcn.com code example
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> fetchWithErrorHandling() async {
try {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
if (response.statusCode == 200) {
// 请求成功,解析 JSON 数据
var data = jsonDecode(response.body);
print(data);
} else {
// 请求失败
throw Exception('Failed to load data');
}
} catch (e) {
// 捕获异常并处理
print("请求失败: $e");
}
}数据缓存
为了提高应用性能和减少网络流量,可以使用本地缓存来存储经常访问的数据。
使用 Hive 进行本地缓存
Hive 是一个轻量级的键值存储库,适合存储结构化数据。
添加 Hive 依赖
在 pubspec.yaml 文件中添加对 hive 和 hive_flutter 的依赖:
dependencies:
flutter:
sdk: flutter
hive: ^2.0.4
hive_flutter: ^1.1.0初始化 Hive
在应用启动时初始化 Hive:
// www.javascriptcn.com code example
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocumentDir = await path_provider.getApplicationDocumentsDirectory();
Hive.init(appDocumentDir.path);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('数据缓存示例')),
body: Center(child: Text('请查看控制台输出')),
),
);
}
}存储和读取数据
// www.javascriptcn.com code example
import 'package:hive/hive.dart';
import 'dart:convert';
Future<void> saveData(Todo todo) async {
final box = await Hive.openBox('todos');
box.put(todo.id.toString(), todo.toJson());
}
Future<Todo> loadData(int id) async {
final box = await Hive.openBox('todos');
final Map<String, dynamic> data = box.get(id.toString());
return Todo.fromJson(data);
}通过这些方法,您可以有效地实现 Flutter 应用中的网络请求和数据管理功能。希望这些示例能帮助您更好地理解和应用这些技术。