Home > Blockchain >  Flutter graphql query with variable
Flutter graphql query with variable

Time:12-01

I am testing flutter graphql for first time. Here is my query and variables that I am using graphql explorer.

My question is before I pass the query and queryVariables, I need to replace 1001 in queryVariables with parameter value. May I know how I can replace it?

const String query = r'''
  query Albums($where: AlbumWhereInput) {
  albums(where: $where) {
    id
    title
    artist {
      name
    }
  }
}
''';

const String queryVariables = r'''
{
  "where": {
    "artist_id": 1001
  }
}
''';

Future<QueryResult> performQuery(String query,
  {required Map<String, dynamic> variables}) async {
    QueryOptions options =
        QueryOptions(document: gql(query), variables: variables);

    final result = await _client.query(options);

    return result;
 }

CodePudding user response:

You haven't specified what package you're using, so I can't be specific about what is the best way to do this. But generally, you can use something like string interpolation:

final artistId = 1001;
final queryVariables = '''
{
  "where": {
    "artist_id": $artistId
  }
}
''';

Note how we're using a normal string using ''' and not a raw string (r''') to be able to interpolate via $.

  • Related