Implement GraphQL & Flutter

穿精又带淫゛_ 提交于 2021-02-18 03:38:06

问题


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


回答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});



回答2:


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);


来源:https://stackoverflow.com/questions/52433928/implement-graphql-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!