1

Is there a way to implement GraphQL in flutter? I was trying making the API call with the query and variables objects in a JSON object.

type '_InternalLinkedHashMap' is not a subtype of type 'String' in type cast

2 Answers 2

1

I have been using graphql_flutter package for a few weeks now and it seems to work well enough. Here is an example:

import 'package:graphql_flutter/graphql_flutter.dart' show Client, InMemoryCache;
...
Future<dynamic> post(
    String body, {
    Map<String, dynamic> variables,
  }) async {
    final Client client = Client(
      endPoint: endpoint,
      cache: new InMemoryCache(),
    );

    final Future<Map<String, dynamic>> result =
        client.query(query: body, variables: variables);

    return result;
  }

To use just give it the graphql and any variables. i.e. a delete mutation may look like

String deleteMutation =
      '''mutation deleteItem(\$itemId: ID!) {
    deleteItem(input: { itemId: \$itemId}) {
      itemId
    }
  }'''.replaceAll('\n', ' ');

 await post(deleteMutation , variables: <String, dynamic>{'itemId': itemId});
Sign up to request clarification or add additional context in comments.

4 Comments

Does that need await async in methods?
sorry forgot to add.
woudln't this make your life easier to use .gql files for graphql queries? As you'd have syntax tooling.
@aqwert will your graphql client gets created for every post request?
0

This is updated and working solution of @aqwert

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

HttpLink link = HttpLink(uri: /*your url here*/); // you can also use headers for authorization etc. 
GraphQLClient client = GraphQLClient(link: link as Link, cache: InMemoryCache());

QueryOptions query = QueryOptions(
    document:
    r'''
      mutation deleteItem($id: String!) {
        deleteItem(callId: $id)
      }
    ''',
    variables: {'id' : id}
);

var result = await client.query(query);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.