GraphQL Custom Action

I put this together as I was trying to solve how to query a GraphQL API. Not sure if it's the best approach so would love feedback but it does work. It returns a JSON aka dynamic type.

For anyone who uses Hasura, there is also a commented line that shows how to pass custom headers when you want to use the admin secret.

I wish there was a way to add the client via a GraphQLProvider Wrapper around main.dart but there doesn't seem to be. Next I may try creating a simple custom widget that does this and can be used to wrap widgets on a screen that need to react to GraphQL queries, mutations and subscriptions

Would love to see Flutterflow team add native support for GraphQL, I think that would unlock a LOT of use cases. Love Flutterflow in general.

Hope this helps some of you :)

P.S. Can Dart be configured as one of the languages in the code block? lol

// Automatic FlutterFlow imports
import '/backend/schema/structs/index.dart';
import '/actions/actions.dart' as action_blocks;
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:graphql_flutter/graphql_flutter.dart';

Future<dynamic> queryGQL(String query, String token, String apiUrl) async {
  // query a graphql API using a graphql client that passes a bearer token and returns a JSON result

  final HttpLink httpLink =
      //HttpLink(apiUrl, defaultHeaders: {'x-hasura-admin-secret': '$token'});
      HttpLink(apiUrl);


  final AuthLink authLink = AuthLink(
    getToken: () async => 'Bearer $token',
  );


  final Link link = authLink.concat(httpLink);
  final Link link = httpLink;

// Define the GraphQL client
  final GraphQLClient client = GraphQLClient(cache: GraphQLCache(), link: link);

// Define the GraphQL query options
  final QueryOptions options = QueryOptions(
    document: gql(query),
  );

// Execute the GraphQL query
  final QueryResult result = await client.query(options);

// Check if the query was successful
  if (result.hasException) {
    throw result.exception.toString();
  }
}
4
2 replies