Home > OS >  Decode GraphQL query result in dart
Decode GraphQL query result in dart

Time:12-22

This might have been asked before, but I am not able to make my query work even after following the steps mentioned in one of the posts here in Stackoverflow. Here is the graphql query I am calling on the button click

void findUserOnBol() async {
  try {
      String graphQLDocument = '''query findUser(\$id: ID!) {
      findUser(userId: \$id) {
      id
    }
  }''';
      var operation = Amplify.API.query(
        request: GraphQLRequest<String>(
            document: graphQLDocument,
            apiName: 'API_KEY',
            variables: {'id': 'USER-14161234567'}));

    var response = await operation.response;
    Map<String, dynamic> data = jsonDecode(response.data) as Map<String,dynamic>;
    print(data);
    print(data['id]);
  } on ApiException catch (e) {
    print('Query failed: $e');
  }
}

In the above query the print(data['id']) statement always return null even when there is data returned, below is the result of the operation -

flutter: {findUser: {id: USER-14161234567}} //printing data returns valid data
flutter: null //printing data['id'] returns null.

CodePudding user response:

Data: {findUser: {id: USER-14161234567}}

The id is not at the top level of the map, you should first get the ['findUser'] key and then the ['id'] as this is nested.

    print(data);
    print(data['findUser']['id']);
  • Related