graphql_flutter: Client Setup and Querying
graphql_flutter connects your app to a GraphQL API via a client-provider-widget pattern. You provide a configured GraphQLClient to a GraphQLProvider, then use Query widgets to fetch data declaratively.
WHY IT EXISTS To provide a declarative, widget-based way for Flutter apps to communicate with GraphQL APIs. It abstracts away the manual HTTP requests and state management involved in data fetching, caching, and UI updates, bringing the powerful patterns of clients like Apollo to the Flutter ecosystem.
THE MENTAL MODEL Think of it like the Provider package, but for your API data. You configure a single GraphQLClient with connection and caching rules, provide it once at the top of your app, and then "ask" for data anywhere in the widget tree using widgets like Query. The library handles the loading, error, and success states for you.
HOW IT WORKS The core setup involves three parts. First, the Link, which defines how to reach your server; HttpLink is common, and you can chain it with AuthLink for tokens. Second, the GraphQLCache, which stores responses to avoid re-fetching; GraphQLCache(store: HiveStore()) provides persistent on-device caching. Third, these are combined into a GraphQLClient. This client is then passed to a GraphQLProvider widget, typically wrapping your MaterialApp, making it available to the entire widget tree.
WHEN TO USE IT Use graphql_flutter when your backend is a GraphQL API and you want a robust client that handles caching, optimistic UI updates, and subscriptions out of the box. The Query, Mutation, and Subscription widgets integrate cleanly into the declarative Flutter widget model, rebuilding your UI automatically when data changes.
WHEN NOT TO USE IT For simple REST APIs, a basic HTTP client like dio or http is a better fit. If you need absolute, low-level control over every network request and caching logic and don't want the abstractions of a full client, you might prefer a lighter solution built directly on a standard HTTP package.
ONE CANONICAL EXAMPLE To fetch data, you use the Query widget. It takes QueryOptions which specify the GraphQL document and any variables. The document, a multiline string containing your query, MUST be wrapped in the gql() function, like document: gql(myQueryString). The widget's builder function receives the QueryResult and is called whenever the state changes (loading, has data, or has error), allowing you to return the appropriate UI for each case, like if (result.isLoading) { return CircularProgressIndicator(); }.
Read the original → pub.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.