简体   繁体   中英

Flutter passing variable to GraphQl query and getting error

This is a very simple GraphQl query which that work fine in graphql_playground or RestClient applications

type Query {
    user(id: ID @eq): User @find(model:"App\\Models\\User")
}


type User {
    id: ID!
    name: String
    email: String
}

now inside Flutter i want to use this query with passing any id for user method and when i try to do this i get this error:

The following SourceSpanException was thrown building UserList(dirty):
Error on line 1, column 23: Expected an argument name
  ╷
1 │           query{ user($id : Int!){
  │                       ^
  ╵

my code:

class UserList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Query(
      options: QueryOptions(
        document: gql(r'''
          query{ user($id : Int!){
            name
            id
          }
          }
        '''),
        variables:{
          'id': 9,
        },
      ),
      builder: (
        QueryResult result, {
        Future<QueryResult> Function(FetchMoreOptions)? fetchMore,
        Future<QueryResult?> Function()? refetch
      }) {
        if (result.data != null){
          print(result.data);
        }
        /// return widget
      },
    );
  }
}

Your query in the client does not seem to be correct for handling variables. Check https://graphql.org/learn/queries/#variables . Here is how it probably should look like for your client:

query GetUser($id: Int!) { 
    user(id : $id) {
        name
        id
    }
}

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