Flutter中GraphQL mutation传递对象数组类型不匹配怎么解决?
Flutter 调用GraphQL Mutation传递对象数组的正确实现
第一步:修正Mutation语法错误
你当前定义的mutation变量定义里,$merchantId: String! 后面缺少英文逗号,会直接触发语法校验失败,先修正:
String inviteEmployeeMutation = """ mutation inviteEmployee ( \$storeId: String!, \$merchantId: String!, \$employees: [NewEmployeeInput!]! // 建议加上非空校验避免传空报错 ) { invitationEmployee ( input: { storeId: \$storeId merchantId: \$merchantId employees: \$employees } ) { nodes { id firstName lastName email mobile } } } """;
第二步:正确序列化传递的对象数组
之前传递Dart对象实例列表触发类型不匹配,是因为GraphQL客户端只接收纯JSON结构的入参,不需要额外做编码再解码的操作,只要把每个NewEmployeeInput对象调用toJson()转为纯Map即可:
假设你的NewEmployeeInput类定义如下:
class NewEmployeeInput { final String firstName; final String lastName; final String? email; final String? mobile; NewEmployeeInput({required this.firstName, required this.lastName, this.email, this.mobile}); Map<String, dynamic> toJson() => { "firstName": firstName, "lastName": lastName, "email": email, "mobile": mobile, }; }
传递参数时按如下方式处理:
// 1. 构造员工对象列表 List<NewEmployeeInput> newEmployees = [ NewEmployeeInput(firstName: "张", lastName: "三", email: "zhangsan@example.com", mobile: "13xxxxxxxxx"), NewEmployeeInput(firstName: "李", lastName: "四", email: "lisi@example.com", mobile: "13xxxxxxxxx"), ]; // 2. 转成纯Map数组,直接传给variables的employees字段 final variables = { "storeId": "你的门店ID", "merchantId": "你的商户ID", "employees": newEmployees.map((e) => e.toJson()).toList(), };
第三步:发起请求的正确示例(以graphql_flutter包为例)
final QueryOptions options = QueryOptions( document: gql(inviteEmployeeMutation), variables: variables, ); final result = await client.mutate(options); // 处理返回结果 if (result.hasException) { print(result.exception.toString()); } else { final employees = result.data?['invitationEmployee']['nodes']; // 后续业务逻辑 }
内容的提问来源于stack exchange,提问作者Basel Abuhadrous
相关产品推荐
相关产品推荐

