探索GraphQL与Flutter的完美融合:graphql-flutter
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:flutter/material.dart';
class GraphQLQueryPage extends StatefulWidget {
@override
_GraphQLQueryPageState createState() => _GraphQLQueryPageState();
}
class _GraphQLQueryPageState extends State<GraphQLQueryPage> {
ValueNotifier<GraphQLClient> client = ValueNotifier(
GraphQLClient(
link: HttpLink(
'https://hasura.io/learn/graphql',
),
cache: GraphQLCache(),
),
);
void performQuery() {
client.value.query(QueryOptions(
document: gql(allTodosQuery),
)).then((QueryResult result) {
// 处理查询结果
print('查询结果: ${result.data}');
}).catchError((error) {
// 处理查询错误
print('查询错误: $error');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GraphQL 查询示例'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('执行查询'),
onPressed: performQuery,
),
],
),
),
);
}
}
const String allTodosQuery = r'''
query AllTodos {
todos {
id
title
isCompleted
}
}
''';
这个代码示例展示了如何在Flutter应用程序中使用graphql_flutter
包来执行GraphQL查询。首先,创建了一个GraphQLClient
,并通过HttpLink指定了GraphQL服务器的URL。然后,定义了一个查询字符串allTodosQuery
,它是一个获取所有todos的GraphQL查询。在performQuery
方法中,使用client.query
执行这个查询,并处理结果或错误。这个例子简单明了地展示了如何在Flutter中集成GraphQL查询功能。
评论已关闭