Flutter GraphQL请求插件alice_graphql的使用
Flutter GraphQL 请求插件 alice_graphql 的使用
alice_graphql
是一个用于捕获和存储 HTTP 请求和响应的插件,现在增强了对 GraphQL 的支持。所有你需要连接到 gql
客户端(如 Ferry)所需的信息都在示例文件夹中。
alice_graphql
受到 Chuck 和 Chucker 的启发,能够捕获和存储 HTTP 请求和响应,并通过简单的用户界面查看它们。它支持多种 Dart HTTP 客户端插件和 GraphQL。
支持的 Dart HTTP 客户端插件和 GraphQL
- Dio
- gql_exec
- gql
- Ferry
- HttpClient(来自 dart:io 包)
- Http(来自 http/http 包)
- Chopper
- 通用 HTTP 客户端
特性
- 详细的日志记录每个 HTTP 调用(HTTP 请求,HTTP 响应)
- 检查器 UI 查看 HTTP 调用
- 将 HTTP 调用保存到文件
- 统计信息
- 在 HTTP 调用时通知
- 支持 Dart 中常用的 HTTP 客户端
- 错误处理
- 设备摇动以打开检查器
- HTTP 调用搜索
- Flutter/Android 日志
安装
- 将以下依赖项添加到你的
pubspec.yaml
文件中:
dependencies:
alice_graphql: ^0.4.1
- 安装它:
$ flutter packages get
- 导入包:
import 'package:alice_graphql_graphql/alice_graphql.dart';
使用
alice_graphql
配置
- 创建
alice_graphql
实例:
Alice alice = Alice();
- 添加导航键到你的应用程序:
MaterialApp(
navigatorKey: alice.getNavigatorKey(),
home: ...,
);
你需要添加此导航键以便显示检查器 UI。你也可以在 alice_graphql
中使用自己的导航键:
Alice alice = Alice(showNotification: true, navigatorKey: yourNavigatorKeyHere);
如果你需要延迟传递导航键,可以使用:
alice.setNavigatorKey(yourNavigatorKeyHere);
这是运行 alice_graphql
所需的最小配置。可以在 alice_graphql
构造函数中设置其他可选参数,这些参数将在下面展示。如果你不想更改任何设置,可以跳到 HTTP 客户端配置部分。
其他设置
你可以设置 showNotification
参数来显示通知。点击此通知将打开检查器:
Alice alice = Alice(..., showNotification: true);
你可以设置 showInspectorOnShake
参数来通过摇晃设备打开检查器(默认禁用):
Alice alice = Alice(..., showInspectorOnShake: true);
如果你想传递另一个通知图标,可以使用 notificationIcon
参数。默认值为 @mipmap/ic_launcher
:
Alice alice = Alice(..., notificationIcon: "myNotificationIconResourceName");
如果你想限制保存在内存中的 HTTP 调用的最大数量,可以使用 maxCallsCount
参数:
Alice alice = Alice(..., maxCallsCount: 1000));
如果你想更改 alice_graphql
的方向性,可以使用 directionality
参数。如果该参数设置为 null
,则使用应用的方向性:
Alice alice = Alice(..., directionality: TextDirection.ltr);
如果你想隐藏分享按钮,可以使用 showShareButton
参数:
Alice alice = Alice(..., showShareButton: false);
HTTP 客户端配置
如果你使用的是 Dio,只需添加拦截器:
Dio dio = Dio();
dio.interceptors.add(alice.getDioInterceptor());
如果你使用的是 HttpClient
来自 dart:io
包:
httpClient
.getUrl(Uri.parse("https://jsonplaceholder.typicode.com/posts"))
.then((request) async {
alice.onHttpClientRequest(request);
var httpResponse = await request.close();
var responseBody = await httpResponse.transform(utf8.decoder).join();
alice.onHttpClientResponse(httpResponse, request, body: responseBody);
});
如果你使用的是 http
来自 http/http
包:
http.get('https://jsonplaceholder.typicode.com/posts').then((response) {
alice.onHttpResponse(response);
});
如果你使用的是 Chopper,你需要添加拦截器:
chopper = ChopperClient(
interceptors: [alice.getChopperInterceptor()],
);
注意!alice_graphql
会向请求中添加一个特殊的 alice_graphql_token
头,以便计算正确的 HTTP 调用 ID。
如果你有其他 HTTP 客户端,可以使用通用 HTTP 调用接口:
AliceHttpCall aliceHttpCall = AliceHttpCall(id);
alice.addHttpCall(aliceHttpCall);
手动显示检查器
如果你不使用摇晃或通知,可能需要手动显示检查器:
alice.showInspector();
保存调用
alice_graphql
支持将日志保存到移动设备存储。为了使保存功能工作,你需要在 Android 应用程序清单中添加以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Flutter 日志
如果你想在 alice_graphql
中记录 Flutter 日志,可以使用以下方法:
alice.addLog(log);
alice.addLogs(logList);
检查器状态
检查当前检查器是否打开(已打开/已关闭):
alice.isInspectorOpened();
扩展
你可以使用扩展来缩短 HTTP 和 HTTP 客户端代码。这虽然是可选的,但可能会改善你的代码库。
示例
导入:
import 'package:alice_graphql_graphql/core/alice_graphql_http_client_extensions.dart';
import 'package:alice_graphql_graphql/core/alice_graphql_http_extensions.dart';
使用扩展:
http
.post('https://jsonplaceholder.typicode.com/posts', body: body)
.interceptWithAlice(alice, body: body);
httpClient
.postUrl(Uri.parse("https://jsonplaceholder.typicode.com/posts"))
.interceptWithAlice(alice, body: body, headers: Map());
示例
完整的示例代码见:https://github.com/jhomlala/alice_graphql/blob/master/example/lib/main.dart
要运行项目,你需要在终端中运行以下命令:
flutter pub run build_runner build --delete-conflicting-outputs
更多关于Flutter GraphQL请求插件alice_graphql的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter GraphQL请求插件alice_graphql的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter应用中使用alice_graphql
插件进行GraphQL请求的示例代码。这个示例假设你已经有一个GraphQL服务器,并且你知道如何编写GraphQL查询。
首先,你需要在你的pubspec.yaml
文件中添加alice_graphql
依赖:
dependencies:
flutter:
sdk: flutter
alice_graphql: ^最新版本号 # 请替换为当前最新版本号
然后运行flutter pub get
来安装依赖。
接下来,我们将编写一个简单的Flutter应用,它使用alice_graphql
来发送GraphQL查询请求。
1. 创建GraphQL客户端
首先,我们需要创建一个GraphQL客户端实例。这个实例将用于发送请求到GraphQL服务器。
import 'package:alice_graphql/alice_graphql.dart';
import 'package:http/http.dart' as http;
class GraphQLClient {
final AliceGraphQL _aliceGraphQL;
GraphQLClient({required String endpoint})
: _aliceGraphQL = AliceGraphQL(
client: http.Client(),
link: AliceLink.http(endpoint),
);
Future<Map<String, dynamic>> query(String query, {Map<String, dynamic> variables = const {}}) async {
final result = await _aliceGraphQL.execute(
AliceRequestOptions(
document: gql(query),
variables: variables,
),
);
if (result.hasErrors) {
throw Exception(result.errors!.map((e) => e.message).join('\n'));
}
return result.data!;
}
}
2. 使用GraphQL客户端发送请求
现在我们可以使用这个GraphQL客户端来发送请求。例如,假设我们有一个简单的GraphQL查询来获取用户信息:
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
在Flutter应用中,我们可以这样使用这个查询:
import 'package:flutter/material.dart';
import 'package:your_app/graphql_client.dart'; // 假设你将上面的代码保存在graphql_client.dart文件中
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late GraphQLClient _graphQLClient;
String? _userId;
String? _userName;
String? _userEmail;
@override
void initState() {
super.initState();
_graphQLClient = GraphQLClient(endpoint: 'https://your-graphql-endpoint.com/graphql');
_fetchUserData(userId: '1'); // 假设我们有一个用户ID为1的用户
}
Future<void> _fetchUserData({required String userId}) async {
setState(() {
_userId = userId;
_userName = null;
_userEmail = null;
});
try {
final result = await _graphQLClient.query(
'''
query GetUser(\$id: ID!) {
user(id: \$id) {
id
name
email
}
}
''',
variables: {'id': userId},
);
final user = result['user'] as Map<String, dynamic>;
setState(() {
_userName = user['name'];
_userEmail = user['email'];
});
} catch (e) {
print('Error fetching user data: $e');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter GraphQL Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('User ID: $_userId'),
SizedBox(height: 16),
Text('Name: $_userName'),
SizedBox(height: 8),
Text('Email: $_userEmail'),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _fetchUserData(userId: '1'), // 你可以更改用户ID来测试
tooltip: 'Fetch User Data',
child: Icon(Icons.refresh),
),
),
);
}
}
总结
这个示例展示了如何使用alice_graphql
插件在Flutter应用中发送GraphQL查询请求。我们创建了一个GraphQL客户端,并使用它来发送一个简单的查询来获取用户信息。然后,我们在Flutter UI中显示了获取到的用户信息。
请根据你的实际需求调整代码,例如处理不同的查询、变更、订阅等。