Flutter JSON REST API客户端插件json_rest_api_client的使用
Flutter JSON REST API客户端插件json_rest_api_client的使用
Json REST API Client
轻松实现一个用于JSON REST API的客户端库。
使用
创建你的客户端
final dummyApiClientV1 = JsonRestApiClient(Uri.parse('http://dummy.restapiexample.com/api/v1'));
执行带有可选查询参数的GET请求
让JsonRestApiClient处理查询组件编码。
final response1 = await dummyApiClientV1.request(
'GET',
'/employee/1',
queryParameters: {'foo': 'bar'}
);
执行其他任何请求并发送JSON数据
final response2 = await dummyApiClientV1.request(
'POST',
'/create',
json: {
'employee_name': 'Tiger Nixon',
'employee_salary': 320800,
'employee_age': 61,
},
);
你也可以发送数组
final response2 = await dummyApiClientV1.request(
'PATCH',
'/sendarray',
json: ['foo', 'bar'],
);
完整示例Demo
以下是完整的示例代码:
import 'package:json_rest_api_client/json_rest_api_client.dart';
void main() async {
// 创建客户端实例
final dummyApiClientV1 = JsonRestApiClient(Uri.parse('http://dummy.restapiexample.com/api/v1'));
// 打印请求结果
print('Request data');
// 发送GET请求
final response1 = await dummyApiClientV1.request(
'GET',
'/employee/1',
);
print(response1.jsonObject); // 输出响应的JSON对象
// 打印写入数据的结果
print('Write data');
// 发送POST请求
final response2 = await dummyApiClientV1.request(
'POST',
'/create',
json: {
'employee_name': 'Tiger Nixon',
'employee_salary': 320800,
'employee_age': 61,
},
);
print(response2.jsonObject); // 输出响应的JSON对象
return;
}
更多关于Flutter JSON REST API客户端插件json_rest_api_client的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter JSON REST API客户端插件json_rest_api_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter应用中使用json_rest_api_client
插件来与JSON REST API进行交互的示例代码。假设你已经在pubspec.yaml
文件中添加了json_rest_api_client
依赖并运行了flutter pub get
。
1. 添加依赖
首先,确保你的pubspec.yaml
文件中包含以下依赖:
dependencies:
flutter:
sdk: flutter
json_rest_api_client: ^x.y.z # 请替换为最新版本号
2. 创建API服务
创建一个新的Dart文件(例如api_service.dart
),用于定义你的API接口。
import 'package:json_rest_api_client/json_rest_api_client.dart';
part 'api_service.g.dart';
@RestApi()
abstract class ApiService {
factory ApiService() => _ApiService();
@GET("/users")
Future<List<User>> getUsers();
@POST("/users")
Future<User> createUser(@Body() User user);
}
@JsonSerializable()
class User {
String? id;
String name;
String email;
User({required this.name, required this.email, this.id});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
运行以下命令生成所需的代码:
flutter pub run build_runner build
3. 使用API服务
在你的主文件(例如main.dart
)中,使用生成的API服务来调用REST API。
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'api_service.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter JSON REST API Client Example'),
),
body: Center(
child: MyHomePage(),
),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late ApiService apiService;
List<User>? users;
@override
void initState() {
super.initState();
apiService = ApiService();
fetchUsers();
}
Future<void> fetchUsers() async {
try {
users = await apiService.getUsers();
setState(() {});
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Users:'),
if (users != null)
ListView.builder(
shrinkWrap: true,
itemCount: users!.length,
itemBuilder: (context, index) {
User user = users![index];
return ListTile(
title: Text('Name: ${user.name}'),
subtitle: Text('Email: ${user.email}'),
);
},
),
ElevatedButton(
onPressed: () {
createUser();
},
child: Text('Create User'),
),
],
);
}
Future<void> createUser() async {
User newUser = User(name: 'John Doe', email: 'john.doe@example.com');
try {
User createdUser = await apiService.createUser(newUser);
setState(() {
users = [...users!, createdUser];
});
} catch (e) {
print(e);
}
}
}
4. 配置Dio(如果需要)
json_rest_api_client
通常使用dio
作为HTTP客户端,你可以根据需要配置它。例如,在api_service.dart
文件的顶部添加以下代码来配置基础URL和拦截器:
import 'package:dio/dio.dart';
import 'package:json_rest_api_client/json_rest_api_client.dart';
Dio dio = Dio(
BaseOptions(
baseUrl: 'https://your-api-base-url.com', // 替换为你的API基础URL
connectTimeout: 30000,
receiveTimeout: 30000,
),
);
@RestApi(
dio: dio, // 将dio实例传递给RestApi注解
)
abstract class ApiService {
// ... 其他代码保持不变
}
5. 运行应用
现在,你可以运行你的Flutter应用,并看到它调用你的REST API并显示用户列表。
请注意,这只是一个基本示例,你可能需要根据实际的API端点和数据结构进行调整。