简体   繁体   中英

Flutter graphql query with variable

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

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 $ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM