### GraphQL Flutter Demo App Entry Point Source: https://pub.dev/packages/graphql_flutter/example This is the main entry point for the GraphQL Flutter demo application. It sets up the MaterialApp with a theme and provides navigation to different example screens. ```dart import 'package:flutter/material.dart'; import 'package:trash_themes/themes.dart'; import './graphql_bloc/main.dart' show GraphQLBlocPatternScreen; import './graphql_widget/main.dart' show GraphQLWidgetScreen; import 'fetchmore/main.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GraphQL Flutter Demo', theme: DraculaTheme().makeDarkTheme(context: context), home: Builder( builder: (BuildContext context) => Scaffold( appBar: AppBar( title: const Text('GraphQL Demo App'), ), body: Center( child: Column( children: [ Spacer(), Flexible( child: ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (BuildContext context) => GraphQLBlocPatternScreen(), ), ); }, child: const Text('GraphQL BloC pattern'), )), Spacer(), Flexible( child: ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (BuildContext context) => const GraphQLWidgetScreen(), ), ); }, child: const Text('GraphQL Widget'), )), Spacer(), Flexible( child: ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (BuildContext context) => const FetchMoreWidgetScreen(), ), ); }, child: const Text('Fetchmore (Pagination) Example'), )), ], ), ), ), ), ); } } ``` -------------------------------- ### Using GraphQLConsumer to Access Client Source: https://pub.dev/packages/graphql_flutter This example demonstrates how to use the `GraphQLConsumer` widget to access the `GraphQLClient` instance from the widget's context. This is useful for direct cache manipulation or other client-specific operations. ```dart ... return GraphQLConsumer( builder: (GraphQLClient client) { // do something with the client return Container( child: Text('Hello world'), ); }, ); ... ``` -------------------------------- ### Advanced Mutation with Cache Update Source: https://pub.dev/packages/graphql_flutter This example demonstrates a more complex mutation scenario, including conditional mutation selection, detailed cache updates using `writeFragment`, and handling operation exceptions. It also shows how to integrate optimistic results. ```dart // final Map repository; // final bool optimistic; // Map extractRepositoryData(Map data); // Map get expectedResult; Mutation( options: MutationOptions( document: gql(starred ? mutations.removeStar : mutations.addStar), update: (cache, result) { if (result.hasException) { print(result.exception); } else { final updated = { ...repository, ...extractRepositoryData(result.data), }; cache.writeFragment( Fragment( document: gql( ''' fragment fields on Repository { id name viewerHasStarred } ''', // helper for constructing FragmentRequest )).asRequest(idFields: { '__typename': updated['__typename'], 'id': updated['id'], }), data: updated, broadcast: false, ); } }, onError: (OperationException error) { }, onCompleted: (dynamic resultData) { }, ), builder: (RunMutation toggleStar, QueryResult result) { return ListTile( leading: starred ? const Icon( Icons.star, color: Colors.amber, ) : const Icon(Icons.star_border), trailing: result.isLoading || optimistic ? const CircularProgressIndicator() : null, title: Text(repository['name'] as String), onTap: () { toggleStar( {'starrableId': repository['id']}, optimisticResult: expectedResult, ); }, ); }, ) ``` -------------------------------- ### GraphQL Subscription with useSubscription Hook Source: https://pub.dev/packages/graphql_flutter This example illustrates using the `useSubscription` hook for consuming GraphQL subscriptions within a `HooksWidget`. It provides a concise way to manage subscription state and UI updates. ```dart final subscriptionDocument = gql( r''' subscription reviewAdded { reviewAdded { stars, commentary, episode } } ''', ); class MyHomePage extends HooksWidget { @override Widget build(BuildContext context) { final result = useSubscription( SubscriptionOptions( document: subscriptionDocument, ), ); Widget child; if (result.hasException) { child = Text(result.exception.toString()); } else if (result.isLoading) { child = Center( child: const CircularProgressIndicator(), ); } else { child = ResultAccumulator.appendUniqueEntries( latest: result.data, builder: (context, {results}) => DisplayReviews( reviews: results.reversed.toList(), ), ); } return Scaffold( body: Center(child: child) ); } } ``` -------------------------------- ### Add graphql_flutter to pubspec.yaml Source: https://pub.dev/packages/graphql_flutter/install This is an example of how the graphql_flutter dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: graphql_flutter: ^5.3.0 ``` -------------------------------- ### Define a GraphQL Query String Source: https://pub.dev/packages/graphql_flutter Define your GraphQL query as a multiline string. This example shows a query to read repositories. ```dart String readRepositories = """ query ReadRepositories(\$nRepositories: Int!) { viewer { repositories(last: \$nRepositories) { nodes { id name viewerHasStarred } } } } """; ``` -------------------------------- ### Import graphql_flutter in Dart Source: https://pub.dev/packages/graphql_flutter/install Import the graphql_flutter package into your Dart files to start using its functionalities. ```dart import 'package:graphql_flutter/graphql_flutter.dart'; ``` -------------------------------- ### Define GraphQL Mutation String Source: https://pub.dev/packages/graphql_flutter Define your GraphQL mutation as a Dart string. This example shows how to define an `addStar` mutation. ```dart String addStar = """ mutation AddStar(\\$starrableId: ID!) { addStar(input: {starrableId: \\$starrableId}) { starrable { viewerHasStarred } } } """ ``` -------------------------------- ### Initialize GraphQL Client with Auth and Cache Source: https://pub.dev/packages/graphql_flutter Set up a `GraphQLClient` by combining an `HttpLink` with an `AuthLink` for authentication and a `GraphQLCache` with `HiveStore` for persistence. Ensure Hive is initialized for Flutter. ```dart import 'package:graphql_flutter/graphql_flutter.dart'; void main() async { // We're using HiveStore for persistence, // so we need to initialize Hive. await initHiveForFlutter(); final HttpLink httpLink = HttpLink( 'https://api.github.com/graphql', ); final AuthLink authLink = AuthLink( getToken: () async => 'Bearer ', // OR // getToken: () => 'Bearer ', ); final Link link = authLink.concat(httpLink); ValueNotifier client = ValueNotifier( GraphQLClient( link: link, // The default store is the InMemoryStore, which does NOT persist to disk cache: GraphQLCache(store: HiveStore()), ), ); ... } ... ``` -------------------------------- ### Check Java Version Source: https://pub.dev/packages/graphql_flutter Run this command to verify your Java Development Kit version. Ensure it is set to Java 17 for compatibility. ```bash java -version ``` -------------------------------- ### GraphQL Client with Authentication Link Source: https://pub.dev/packages/graphql_flutter/changelog Demonstrates how to configure a GraphQL client with an authentication link to handle token-based authentication. The `getToken` function is called before each request to fetch the authentication token. ```dart final HttpLink httpLink = HttpLink( uri: 'https://api.github.com/graphql', ); final AuthLink authLink = AuthLink( getToken: () async => 'Bearer $YOUR_PERSONAL_ACCESS_TOKEN', ); final Link link = authLink.concat(httpLink); GraphQLClient client = GraphQLClient( cache: NormalizedInMemoryCache( dataIdFromObject: typenameDataIdFromObject, ), link: link, ); ``` -------------------------------- ### Wrap App with GraphQLProvider Source: https://pub.dev/packages/graphql_flutter Wrap your `MaterialApp` or relevant widget tree with `GraphQLProvider` to make the GraphQL client accessible to `Query` and `Mutation` widgets. ```dart ... return GraphQLProvider( client: client, child: MaterialApp( title: 'Flutter Demo', ... ), ); ... ``` -------------------------------- ### GraphQL Subscription with Subscription Widget Source: https://pub.dev/packages/graphql_flutter This snippet shows how to define a GraphQL subscription document and use the `Subscription` widget to consume real-time data. It includes handling loading states, exceptions, and displaying unique results. ```dart final subscriptionDocument = gql( r''' subscription reviewAdded { reviewAdded { stars, commentary, episode } } ''', ); class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Subscription( options: SubscriptionOptions( document: subscriptionDocument, ), builder: (result) { if (result.hasException) { return Text(result.exception.toString()); } if (result.isLoading) { return Center( child: const CircularProgressIndicator(), ); } // ResultAccumulator is a provided helper widget for collating subscription results. // careful though! It is stateful and will discard your results if the state is disposed return ResultAccumulator.appendUniqueEntries( latest: result.data, builder: (context, {results}) => DisplayReviews( reviews: results.reversed.toList(), ), ); } ), ) ); } } ``` -------------------------------- ### GraphQL Hooks for Client, Query Watching, and Mutation Watching Source: https://pub.dev/packages/graphql_flutter This snippet showcases other available hooks: `useGraphQLClient` to access the client instance, `useWatchQuery` for observing query results, and `useWatchMutation` for observing mutation results. ```dart final client = useGraphQLClient(); // Fetch the current client final observableQuery = useWatchQuery(WatchQueryOptions(...)); // Watch a query final mutationObservableQuery = useWatchMutation(WatchQueryOptions(...)); // Watch a query ``` -------------------------------- ### Access Client with GraphqlProvider Source: https://pub.dev/packages/graphql_flutter/changelog Retrieve the GraphQL client instance from the context using GraphqlProvider. This is the recommended way to access the client after version 0.6.0. ```dart Client client = GraphqlProvider.of(context).value; ``` -------------------------------- ### Configure Fetch More Options for Pagination Source: https://pub.dev/packages/graphql_flutter Define FetchMoreOptions to specify variables and an updateQuery function for pagination. The updateQuery function merges new results with existing data. ```dart ... // this is returned by the GitHubs GraphQL API for pagination purpose final Map pageInfo = result.data['search']['pageInfo']; final String fetchMoreCursor = pageInfo['endCursor']; /// **NOTE**: with the addition of strict data structure checking in v4, /// it is easy to make mistakes in writing [updateQuery]. /// /// To mitigate this, [FetchMoreOptions.partial] has been provided. FetchMoreOptions opts = FetchMoreOptions( variables: {'cursor': fetchMoreCursor}, updateQuery: (previousResultData, fetchMoreResultData) { // this function will be called so as to combine both the original and fetchMore results // it allows you to combine them as you would like final List repos = [ ...previousResultData['search']['nodes'] as List, ...fetchMoreResultData['search']['nodes'] as List ]; // to avoid a lot of work, lets just update the list of repos in returned // data with new data, this also ensures we have the endCursor already set // correctly fetchMoreResultData['search']['nodes'] = repos; return fetchMoreResultData; }, ); ... ``` -------------------------------- ### GraphQL Query Definition Source: https://pub.dev/packages/graphql_flutter Define your GraphQL query in a .graphql file. This query fetches repositories for the authenticated viewer. ```graphql query ReadRepositories($nRepositories: Int!) { viewer { repositories(last: $nRepositories) { nodes { id name } } } } ``` -------------------------------- ### Configure Android Build Settings for Java 17 Source: https://pub.dev/packages/graphql_flutter Update `android/app/build.gradle` to target Java 17 for both source and target compatibility, and set the JVM target for Kotlin. ```gradle android { compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } kotlinOptions { jvmTarget = "17" } } ``` -------------------------------- ### Splitting WebSocket Link for Subscriptions Source: https://pub.dev/packages/graphql_flutter This code demonstrates how to split the GraphQL link to handle subscriptions over WebSockets separately from other requests. Ensure this is done before defining your client. ```dart link = Link.split((request) => request.isSubscription, websocketLink, link); ``` -------------------------------- ### Use Mutation Widget for GraphQL Mutations Source: https://pub.dev/packages/graphql_flutter Use the `Mutation` widget to execute GraphQL mutations. Configure `MutationOptions` for the mutation document, cache updates, and completion callbacks. The `builder` function provides a `runMutation` function to trigger the mutation. ```dart Mutation( options: MutationOptions( document: gql(addStar), // this is the mutation string you just created // you can update the cache based on results update: (GraphQLDataProxy cache, QueryResult result) { return cache; }, // or do something with the result.data on completion onCompleted: (dynamic resultData) { print(resultData); }, ), builder: ( RunMutation runMutation, QueryResult result, ) { return FloatingActionButton( onPressed: () => runMutation({ 'starrableId': , }), tooltip: 'Star', child: Icon(Icons.star), ); }, ) ``` -------------------------------- ### Use useQuery Hook for GraphQL Queries with flutter-hooks Source: https://pub.dev/packages/graphql_flutter Integrate GraphQL queries using the useQuery hook from the flutter-hooks package. Provides a reactive approach to data fetching. ```dart // ... final readRespositoriesResult = useQuery( QueryOptions( document: gql(readRepositories), // this is the query string you just created variables: { 'nRepositories': 50, }, pollInterval: const Duration(seconds: 10), ), ); final result = readRespositoriesResult.result; if (result.hasException) { return Text(result.exception.toString()); } if (result.isLoading) { return const Text('Loading'); } List? repositories = result.data?['viewer']?['repositories']?['nodes']; if (repositories == null) { return const Text('No repositories'); } return ListView.builder( itemCount: repositories.length, itemBuilder: (context, index) { final repository = repositories[index]; return Text(repository['name'] ?? ''); }); // ... ``` -------------------------------- ### Optimistic Mutations with GraphQL Source: https://pub.dev/packages/graphql_flutter Implement optimistic mutations by providing an `optimisticResult` to `RunMutation`. This allows the UI to update immediately with the expected result before the server confirms the change. ```dart ... toggleStar( { 'starrableId': repository['id'] }, optimisticResult: { 'action': { 'starrable': {'viewerHasStarred': !starred} } }, ); ... ``` -------------------------------- ### Add graphql_flutter Dependency Source: https://pub.dev/packages/graphql_flutter/install Use this command to add the graphql_flutter package to your Flutter project's dependencies. ```bash $ flutter pub add graphql_flutter ``` -------------------------------- ### Trigger Fetch More with Button Source: https://pub.dev/packages/graphql_flutter Use a button to trigger the fetchMore function, passing the configured FetchMoreOptions to load more data. ```dart RaisedButton( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Load More"), ], ), onPressed: () { fetchMore(opts); }, ) ``` -------------------------------- ### Update Fragment and FragmentRequest API Source: https://pub.dev/packages/graphql_flutter/changelog This snippet demonstrates the updated API for writing fragments to the cache, now using FragmentRequest for a more normalized approach. It shows the transition from the older method to the new one. ```dart final fragDoc = gql(...); final idFields = { '__typename': 'MyType', 'id': 1 } final fragmentData = { 'myField': 'updatedValue', 'someNewField': [ {'newData': false} ], }; + // or Fragment(document: fragDoc).asRequest(idFields: idFields) + final fragmentRequest = FragmentRequest( + fragment: Fragment( + document: fragDoc, + ), + idFields: idFields, + ); cache.writeFragment( - fragment: fragDoc, - idFields: idFields, + fragmentRequest, data: fragmentData, ); ``` -------------------------------- ### Use Query Widget for GraphQL Queries Source: https://pub.dev/packages/graphql_flutter Integrate a GraphQL query into a Flutter widget using the Query widget. Handles loading, error, and data states. Supports manual refetching and pagination. ```dart // ... Query( options: QueryOptions( document: gql(readRepositories), // this is the query string you just created variables: { 'nRepositories': 50, }, pollInterval: const Duration(seconds: 10), ), // Just like in apollo refetch() could be used to manually trigger a refetch // while fetchMore() can be used for pagination purpose builder: (QueryResult result, { VoidCallback? refetch, FetchMore? fetchMore }) { if (result.hasException) { return Text(result.exception.toString()); } if (result.isLoading) { return const Text('Loading'); } List? repositories = result.data?['viewer']?['repositories']?['nodes']; if (repositories == null) { return const Text('No repositories'); } return ListView.builder( itemCount: repositories.length, itemBuilder: (context, index) { final repository = repositories[index]; return Text(repository['name'] ?? ''); }); }, ); // ... ``` -------------------------------- ### Use useMutation Hook for GraphQL Mutations Source: https://pub.dev/packages/graphql_flutter The `useMutation` hook provides a similar functionality to the `Mutation` widget for executing GraphQL mutations within a functional component. It returns a `runMutation` function to trigger the mutation. ```dart // ... final addStarMutation = useMutation( MutationOptions( document: gql(addStar), // this is the mutation string you just created // you can update the cache based on results update: (GraphQLDataProxy cache, QueryResult result) { return cache; }, // or do something with the result.data on completion onCompleted: (dynamic resultData) { print(resultData); }, ), ); return FloatingActionButton( onPressed: () => addStarMutation.runMutation({ 'starrableId': , }), tooltip: 'Star', child: Icon(Icons.star), ); // ... ``` -------------------------------- ### Update Gradle Wrapper Source: https://pub.dev/packages/graphql_flutter Modify the `gradle-wrapper.properties` file to specify Gradle 8.4. This ensures the project uses the correct Gradle version for building. ```properties distributionUrl=https://services.gradle.org/distributions/gradle-8.4-bin.zip ``` -------------------------------- ### Generated Hook Usage in Flutter Source: https://pub.dev/packages/graphql_flutter Use the generated `useQueryReadRepositories` hook to query data in your Flutter application. Handles loading, error states, and provides parsed data. ```dart final queryResult = useQueryReadRepositories( OptionsQueryReadRepositories( variables: VariablesQueryReadRepositories( nRepositories: 10 ) ) ); if (queryResult.result.hasException) { return Text(result.exception.toString()); } if (queryResult.result.isLoading) { return Text(text: "LOADING"); } final data = queryResult.result.parsedData; return Column( children: data?.viewer.repositores.nodes.map((node) => Text(text: node.name)); ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.