Flutter 中的 GraphQL 客户端:使用 graphql_flutter

Flutter 中的 GraphQL 客户端:使用 graphql_flutter

5 回复

graphql_flutter 是 Flutter 中用于 GraphQL 的客户端库。

更多关于Flutter 中的 GraphQL 客户端:使用 graphql_flutter的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,可以使用 graphql_flutter 库作为 GraphQL 客户端,方便地与 GraphQL API 进行交互,支持查询、变更和订阅操作。

在 Flutter 中使用 graphql_flutter 包可以方便地集成 GraphQL 客户端。首先,在 pubspec.yaml 中添加依赖:

dependencies:
  graphql_flutter: ^5.1.0

然后,初始化 GraphQL 客户端并提供给应用:

import 'package:graphql_flutter/graphql_flutter.dart';

final HttpLink httpLink = HttpLink('https://your-graphql-endpoint.com/graphql');

final ValueNotifier<GraphQLClient> client = ValueNotifier(
  GraphQLClient(
    cache: GraphQLCache(),
    link: httpLink,
  ),
);

void main() {
  runApp(
    GraphQLProvider(
      client: client,
      child: MyApp(),
    ),
  );
}

你可以使用 QueryMutation 组件来执行查询和变更操作。例如:

Query(
  options: QueryOptions(
    document: gql('''
      query GetBooks {
        books {
          title
          author
        }
      }
    '''),
  ),
  builder: (QueryResult result, { VoidCallback? refetch, FetchMore? fetchMore }) {
    if (result.hasException) {
      return Text(result.exception.toString());
    }

    if (result.isLoading) {
      return CircularProgressIndicator();
    }

    final List<dynamic> books = result.data!['books'];
    return ListView.builder(
      itemCount: books.length,
      itemBuilder: (context, index) {
        final book = books[index];
        return ListTile(
          title: Text(book['title']),
          subtitle: Text(book['author']),
        );
      },
    );
  },
);

通过这种方式,你可以轻松地在 Flutter 应用中集成 GraphQL。

graphql_flutter 是 Flutter 中用于 GraphQL 的客户端库。

在 Flutter 中使用 GraphQL 客户端,graphql_flutter 是一个非常流行的库,它允许你轻松地与 GraphQL API 进行交互。以下是如何在 Flutter 项目中使用 graphql_flutter 的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 graphql_flutter 依赖:

dependencies:
  flutter:
    sdk: flutter
  graphql_flutter: ^5.0.0

然后运行 flutter pub get 来安装依赖。

2. 配置 GraphQL 客户端

在你的 Flutter 应用中,你需要配置一个 GraphQLClient 实例。通常你可以在 main.dart 文件中进行配置:

import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

void main() {
  final HttpLink httpLink = HttpLink(
    'https://your-graphql-endpoint.com/graphql',
  );

  final ValueNotifier<GraphQLClient> client = ValueNotifier(
    GraphQLClient(
      link: httpLink,
      cache: GraphQLCache(store: InMemoryStore()),
    ),
  );

  runApp(MyApp(client: client));
}

class MyApp extends StatelessWidget {
  final ValueNotifier<GraphQLClient> client;

  MyApp({required this.client});

  @override
  Widget build(BuildContext context) {
    return GraphQLProvider(
      client: client,
      child: MaterialApp(
        title: 'Flutter GraphQL',
        home: HomePage(),
      ),
    );
  }
}

3. 使用 GraphQL 查询

你可以在任何 Widget 中使用 QueryMutation 组件来执行 GraphQL 查询或变更。

查询示例:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GraphQL Example'),
      ),
      body: Query(
        options: QueryOptions(
          document: gql('''
            query GetBooks {
              books {
                title
                author
              }
            }
          '''),
        ),
        builder: (QueryResult result, {fetchMore, refetch}) {
          if (result.hasException) {
            return Text(result.exception.toString());
          }

          if (result.isLoading) {
            return Center(child: CircularProgressIndicator());
          }

          final books = result.data?['books'];

          return ListView.builder(
            itemCount: books.length,
            itemBuilder: (context, index) {
              final book = books[index];
              return ListTile(
                title: Text(book['title']),
                subtitle: Text(book['author']),
              );
            },
          );
        },
      ),
    );
  }
}

变更示例:

class AddBookPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add Book'),
      ),
      body: Mutation(
        options: MutationOptions(
          document: gql('''
            mutation AddBook($title: String!, $author: String!) {
              addBook(title: $title, author: $author) {
                title
                author
              }
            }
          '''),
        ),
        builder: (RunMutation runMutation, QueryResult? result) {
          return Column(
            children: [
              TextField(
                decoration: InputDecoration(labelText: 'Title'),
                onChanged: (value) {
                  // 处理输入逻辑
                },
              ),
              TextField(
                decoration: InputDecoration(labelText: 'Author'),
                onChanged: (value) {
                  // 处理输入逻辑
                },
              ),
              ElevatedButton(
                onPressed: () {
                  runMutation({
                    'title': 'Book Title',
                    'author': 'Book Author',
                  });
                },
                child: Text('Add Book'),
              ),
            ],
          );
        },
      ),
    );
  }
}

4. 使用 GraphQL 订阅

graphql_flutter 也支持 GraphQL 订阅。你可以使用 Subscription 组件来监听实时数据。

class SubscriptionExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Subscription Example'),
      ),
      body: Subscription(
        options: SubscriptionOptions(
          document: gql('''
            subscription OnBookAdded {
              bookAdded {
                title
                author
              }
            }
          '''),
        ),
        builder: (QueryResult result) {
          if (result.hasException) {
            return Text(result.exception.toString());
          }

          if (result.isLoading) {
            return Center(child: CircularProgressIndicator());
          }

          final book = result.data?['bookAdded'];

          return ListTile(
            title: Text(book['title']),
            subtitle: Text(book['author']),
          );
        },
      ),
    );
  }
}

通过以上步骤,你可以在 Flutter 应用中轻松地使用 graphql_flutter 来与 GraphQL API 进行交互。

回到顶部