Flutter GraphQL与状态管理插件graphql_flutter_bloc的使用

发布于 1周前 作者 bupafengyu 来自 Flutter

Flutter GraphQL与状态管理插件graphql_flutter_bloc的使用

graphql_flutter_bloc

graphql_flutter_bloc 是一个用于处理 graphql_flutter 流的状态管理插件,提供了改进后的状态处理。

安装

  • 使用 v0.3.* 适用于 graphql_flutter v3(此版本已不再支持。
  • 使用 v > 0.4.* 适用于 graphql_flutter v4。

如何使用

克隆此仓库并启动 example 项目。 这将帮助您了解如何使用此库进行 QueryMutation

示例代码

import 'dart:io';

import 'package:example/bloc_mutation.dart';
import 'package:example/bloc_mutation_optimistic.dart';
import 'package:example/bloc_query.dart';
import 'package:example/bloc_search_query.dart';
import 'package:example/bloc_subscription.dart';
import 'package:example/hive_init.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initHiveForFlutter();

  runApp(const MyApp());
}

String get host {
  if (Platform.isAndroid) {
    return '110.0.2.2';
  } else {
    return 'localhost';
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        'bloc-query': (_) => const BlocQuery(),
        'bloc-mutation': (_) => const BlocMutation(),
        'bloc-mutation-optimistic': (_) => const BlocMutationOptimistic(),
        'bloc-search-query': (_) => const BlocSearchQuery(),
        'bloc-subscription': (_) => const BlocSubscription(),
      },
      home: const Home(),
    );
  }
}

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Select example"),
      ),
      body: ListView(
        childrenen: [
          ListTile(
            title: const Text('BLOC Query'),
            subtitle: const Text('query, fetchMore, refetch'),
            onTap: () =&gt; Navigator.of(context).pushNamed('bloc-query'),
          ),
          const Divider(),
          ListTile(
            title: const Text('BLOC Mutation'),
            subtitle: const Text('simple form + submit to call mutation'),
            onTap: () =&gt; Navigator.of(context).pushNamed(
              'bloc-mutation',
            ),
          ),
          const Divider(),
          ListTile(
            title: const Text('BLOC Mutation Optimistic'),
            subtitle: const Text(
                'simple form + submit to call mutation + optimistic results'),
            onTap: () =&gt;
                Navigator.of(context).pushNamed('bloc-mutation-optimistic'),
          ),
          const Divider(),
          ListTile(
            title: const Text('BLOC Search Query'),
            onTap: () =&gt; Navigator.of(context).pushNamed('bloc-search-query'),
          ),
          const Divider(),
          ListTile(
            title: const Text('BLOC Subscription'),
            onTap: () =&gt; Navigator.of(context).pushNamed('bloc-subscription'),
          ),
          const Divider(),
        ],
      ),
    );
  }
}

更多关于Flutter GraphQL与状态管理插件graphql_flutter_bloc的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter GraphQL与状态管理插件graphql_flutter_bloc的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用GraphQL与状态管理插件graphql_flutter_bloc的示例代码。这个示例将展示如何设置一个基本的GraphQL查询,并使用Bloc模式管理状态。

首先,确保你的pubspec.yaml文件中包含以下依赖项:

dependencies:
  flutter:
    sdk: flutter
  flutter_bloc: ^8.0.0
  graphql_flutter: ^5.0.0
  graphql: ^5.0.0

然后,运行flutter pub get来安装这些依赖项。

1. 定义GraphQL查询

创建一个文件queries.dart来定义你的GraphQL查询:

import 'package:graphql/client.dart';

final String getUserDataQuery = r'''
  query GetUserData($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
''';

class GetUserDataOptions extends QueryOptions {
  GetUserDataOptions({required String id}) : super(
    variables: {'id': id},
    document: gql(getUserDataQuery),
  );
}

2. 创建Bloc和事件/状态

接下来,创建一个Bloc来处理GraphQL查询的状态。我们将创建三个文件:user_event.dartuser_state.dartuser_bloc.dart

user_event.dart

part of 'user_bloc.dart';

abstract class UserEvent {}

class FetchUserData extends UserEvent {
  final String userId;
  FetchUserData({required this.userId});
}

user_state.dart

part of 'user_bloc.dart';

class UserState {
  final bool isLoading;
  final UserData? userData;
  final String? errorMessage;

  UserState({
    required this.isLoading,
    this.userData,
    this.errorMessage,
  });

  factory UserState.initial() => UserState(
    isLoading: false,
    userData: null,
    errorMessage: null,
  );

  factory UserState.loading() => UserState(
    isLoading: true,
    userData: null,
    errorMessage: null,
  );

  factory UserState.error(String errorMessage) => UserState(
    isLoading: false,
    userData: null,
    errorMessage: errorMessage,
  );

  factory UserState.loaded(UserData userData) => UserState(
    isLoading: false,
    userData: userData,
    errorMessage: null,
  );
}

class UserData {
  final String id;
  final String name;
  final String email;

  UserData({required this.id, required this.name, required this.email});

  factory UserData.fromJson(Map<String, dynamic> json) {
    return UserData(
      id: json['id'] as String,
      name: json['name'] as String,
      email: json['email'] as String,
    );
  }
}

user_bloc.dart

import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'queries.dart';
import 'user_event.dart';
import 'user_state.dart';

part 'user_event.dart';
part 'user_state.dart';

class UserBloc extends Bloc<UserEvent, UserState> {
  final ValueNotifier<GraphQLClient> client;

  UserBloc({required this.client}) : super(UserState.initial()) {
    on<FetchUserData>((event, emit) async {
      emit(UserState.loading());
      try {
        final result = await client.value.query(GetUserDataOptions(id: event.userId));
        if (result.hasException) {
          throw result.exception!;
        }
        emit(UserState.loaded(UserData.fromJson(result.data!['user'] as Map<String, dynamic>)));
      } catch (e) {
        emit(UserState.error(e.toString()));
      }
    });
  }
}

3. 设置GraphQL客户端

在你的主文件(例如main.dart)中设置GraphQL客户端,并提供BlocProvider:

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'queries.dart';
import 'user_bloc.dart';

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

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

  runApp(
    MultiProvider(
      providers: [
        Provider.value(value: client),
        BlocProvider(
          create: (context) => UserBloc(client: client),
        ),
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: UserScreen(),
    );
  }
}

4. 创建用户界面

最后,创建一个用户界面来展示用户数据,并触发GraphQL查询。

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'user_bloc.dart';

class UserScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('User Data')),
      body: Center(
        child: BlocConsumer<UserBloc, UserState>(
          listener: (context, state) {},
          builder: (context, state) {
            if (state.isLoading) {
              return CircularProgressIndicator();
            } else if (state.errorMessage != null) {
              return Text('Error: ${state.errorMessage!}');
            } else if (state.userData != null) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('ID: ${state.userData!.id}'),
                  Text('Name: ${state.userData!.name}'),
                  Text('Email: ${state.userData!.email}'),
                ],
              );
            } else {
              return ElevatedButton(
                onPressed: () {
                  context.read<UserBloc>().add(FetchUserData(userId: '1')); // Replace with actual user ID
                },
                child: Text('Fetch User Data'),
              );
            }
          },
        ),
      ),
    );
  }
}

这个示例展示了如何使用graphql_flutterflutter_bloc库在Flutter应用中执行GraphQL查询并管理状态。你可以根据自己的需求进一步扩展和修改这个示例。

回到顶部