如何在Flutter中使用GraphQL发送自定义查询?(附尝试代码)
在Flutter中使用GraphQL发送自定义查询的正确方式
首先修正你提供的查询字符串写法——Dart中使用三重双引号(""" """)包裹字符串时,内部的双引号不需要额外转义,你的代码里多余的转义会导致查询格式错误。修正后的查询如下:
static String mainQuery = """ query { user(id: "your_id") { id name income transactions { id title type currency created_at userId } } } """;
下面是完整的实现流程,以graphql_flutter包为例:
1. 添加依赖
在pubspec.yaml中添加GraphQL依赖(使用最新版本即可):
dependencies: flutter: sdk: flutter graphql_flutter: ^5.1.2
2. 初始化GraphQL客户端
创建全局的GraphQL客户端,连接你的API地址:
import 'package:graphql_flutter/graphql_flutter.dart'; // 替换为你的GraphQL API地址 final HttpLink httpLink = HttpLink('https://your-api-domain.com/graphql'); final ValueNotifier<GraphQLClient> graphQLClient = ValueNotifier( GraphQLClient( link: httpLink, // 缓存配置,用HiveStore需要额外添加hive依赖,也可以用InMemoryStore cache: GraphQLCache(store: HiveStore()), ), );
3. 发送自定义查询并处理结果
使用Query组件来执行查询、处理加载状态和结果展示:
class UserInfoPage extends StatelessWidget { @override Widget build(BuildContext context) { return GraphQLProvider( client: graphQLClient, child: Scaffold( appBar: AppBar(title: const Text('用户信息')), body: Query( options: QueryOptions( document: gql(mainQuery), // 将字符串转为GraphQL文档对象 ), builder: (QueryResult result, {VoidCallback? refetch, FetchMore? fetchMore}) { // 处理加载状态 if (result.isLoading) { return const Center(child: CircularProgressIndicator()); } // 处理错误 if (result.hasException) { return Padding( padding: const EdgeInsets.all(16), child: Text('查询失败: ${result.exception.toString()}'), ); } // 解析返回数据 final user = result.data?['user']; if (user == null) { return const Center(child: Text('未找到该用户')); } // 渲染用户信息 return ListView( padding: const EdgeInsets.all(16), children: [ ListTile(title: Text('ID: ${user['id']}')), ListTile(title: Text('姓名: ${user['name']}')), ListTile(title: Text('收入: ${user['income']}')), const SizedBox(height: 16), const Text('交易记录:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), ...(user['transactions'] as List).map((tx) { return ListTile( title: Text(tx['title']), subtitle: Text('类型: ${tx['type']} | 币种: ${tx['currency']}'), ); }), ], ); }, ), ), ); } }
4. 优化:使用动态变量传递参数
硬编码ID不够灵活,推荐用变量传递参数,修改查询为:
static String userQueryWithVars = """ query GetUser(\$userId: ID!) { user(id: \$userId) { id name income transactions { id title type currency created_at userId } } } """;
然后在QueryOptions中传入变量:
options: QueryOptions( document: gql(userQueryWithVars), variables: { 'userId': 'your-dynamic-user-id', // 这里可以传入动态获取的用户ID }, ),
内容的提问来源于stack exchange,提问作者Nijat Namazzade
相关产品推荐
相关产品推荐

