【问题标题】:Implement GraphQL & Flutter实现 GraphQL 和 Flutter
【发布时间】:2019-02-25 06:50:41
【问题描述】:

有没有办法在 Flutter 中实现 GraphQL? 我正在尝试使用 JSON 对象中的查询和变量对象进行 API 调用。

类型“_InternalLinkedHashMap”不是类型转换中“String”类型的子类型

【问题讨论】:

    标签: dart flutter graphql


    【解决方案1】:

    我已经使用graphql_flutter 包几个星期了,它似乎工作得很好。这是一个例子:

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

    要使用它,只需给它 graphql 和任何变量。即删除突变可能看起来像

    String deleteMutation =
          '''mutation deleteItem(\$itemId: ID!) {
        deleteItem(input: { itemId: \$itemId}) {
          itemId
        }
      }'''.replaceAll('\n', ' ');
    
     await post(deleteMutation , variables: <String, dynamic>{'itemId': itemId});
    

    【讨论】:

    • 这需要在方法中等待异步吗?
    • 抱歉忘记添加了。
    • 使用.gql 文件进行graphql 查询难道不会让您的生活更轻松吗?就像你有语法工具一样。
    • @aqwert 您的 graphql 客户端会为每个发布请求创建吗?
    【解决方案2】:

    这是@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);
    

    【讨论】:

      猜你喜欢
      • 2022-06-11
      • 2022-10-22
      • 1970-01-01
      • 2019-10-12
      • 2018-10-18
      • 2021-08-15
      • 1970-01-01
      • 2021-06-25
      • 2021-02-18
      相关资源
      最近更新 更多