Darshit Chokshi
Darshit Chokshi

Reputation: 33

How to call a graphQl "query" from dart file

I am trying to call a network call(GraphQL - Query) using graphQL into flutter, I need to know exact way to acheive this.

Upvotes: 0

Views: 1389

Answers (1)

chunhunghan
chunhunghan

Reputation: 54377

Please use this package https://pub.dev/packages/graphql_flutter

and in example https://pub.dev/packages/graphql_flutter#queries

String readRepositories = """
  query ReadRepositories(\$nRepositories: Int!) {
    viewer {
      repositories(last: \$nRepositories) {
        nodes {
          id
          name
          viewerHasStarred
        }
      }
    }
  }
""";

Query(
  options: QueryOptions(
    document: readRepositories, // this is the query string you just created
    variables: {
      'nRepositories': 50,
    },
    pollInterval: 10,
  ),
  // Just like in apollo refetch() could be used to manually trigger a refetch
  builder: (QueryResult result, { VoidCallback refetch }) {
    if (result.errors != null) {
      return Text(result.errors.toString());
    }

    if (result.loading) {
      return Text('Loading');
    }

    // it can be either Map or List
    List repositories = result.data['viewer']['repositories']['nodes'];

    return ListView.builder(
      itemCount: repositories.length,
      itemBuilder: (context, index) {
        final repository = repositories[index];

        return Text(repository['name']);
    });
  },
);

you can also test example directly https://github.com/zino-app/graphql-flutter/tree/master/examples/starwars

Upvotes: 2

Related Questions