← Back to posts Cover image for Mastering GraphQL in Flutter: Building Type-Safe Clients with Dynamic Field Selections

Mastering GraphQL in Flutter: Building Type-Safe Clients with Dynamic Field Selections

· 6 min read
Weekly Digest

The Flutter news you actually need

No spam, ever. Unsubscribe in one click.

Chris
By Chris

If you’ve worked with GraphQL in Flutter, you’ve likely felt the tension between GraphQL’s dynamic nature and Dart’s static type system. You design a beautiful schema with non-nullable fields, but your generated models end up littered with nullable types (String?, int?) because different queries select different subsets of fields. This undermines null safety and forces defensive programming where it shouldn’t be needed.

The core problem is using a single model class to represent a GraphQL type across all queries. When your Book schema type has 20 fields, but your BookList query only needs id, title, and authorName, your Dart Book class must make 17 fields nullable to accommodate that query. This creates a misleading API—your code suggests summary might be null when the schema guarantees it exists.

The Solution: Query-Specific Models

The solution is to generate a unique Dart class for each query, reflecting exactly what fields you requested. This approach gives you compile-time guarantees about what data is available.

Consider this GraphQL schema:

type Author {
  id: ID!
  name: String!
  bio: String
}

type Book {
  id: ID!
  title: String!
  year: Int!
  author: Author!
  pageCount: Int!
  summary: String!
}

Instead of a one-size-fits-all Book class, generate specific classes for each query:

// For a query selecting only id, title, and year
class BookListQuery$Book {
  final String id;
  final String title;
  final int year;
  
  BookListQuery$Book({
    required this.id,
    required this.title,
    required this.year,
  });
}

// For a query with more fields
class BookDetailQuery$Book {
  final String id;
  final String title;
  final int year;
  final BookDetailQuery$Author author;
  final int pageCount;
  
  BookDetailQuery$Book({
    required this.id,
    required this.title,
    required this.year,
    required this.author,
    required this.pageCount,
  });
}

class BookDetailQuery$Author {
  final String id;
  final String name;
  
  BookDetailQuery$Author({
    required this.id,
    required this.name,
  });
}

Now BookListQuery$Book confidently exposes non-nullable fields because you know exactly what was requested. No more guessing if author is present—if you didn’t query it, it’s not in the class.

Handling Fragments for Reusability

A common concern is widget reuse. If you have a BookCard widget that needs book data, how can it accept data from different queries? GraphQL fragments provide the answer.

Define a fragment in your GraphQL:

fragment BookCardData on Book {
  id
  title
  year
  author {
    id
    name
  }
}

Then use it in queries:

query BookList {
  books {
    ...BookCardData
  }
}

query FeaturedBooks {
  featuredBooks {
    ...BookCardData
    isFeatured
  }
}

Your code generator creates an interface or base class for the fragment:

abstract class BookCardData {
  String get id;
  String get title;
  int get year;
  BookCardData$Author get author;
}

class BookListQuery$Book implements BookCardData {
  @override final String id;
  @override final String title;
  @override final int year;
  @override final BookCardData$Author author;
  
  // ... constructor
}

class FeaturedBooksQuery$Book implements BookCardData {
  @override final String id;
  @override final String title;
  @override final int year;
  @override final BookCardData$Author author;
  final bool isFeatured; // Additional field
  
  // ... constructor
}

Now your BookCard widget accepts BookCardData, working with books from any query that includes that fragment.

Dealing with Conditional Fields and Unions

Two challenging areas remain: conditional fields (@include/@skip) and GraphQL unions/interfaces.

For conditional fields, the generated Dart field must be nullable since the server omits it when the condition is false:

query GetBook($withSummary: Boolean!) {
  book(id: "1") {
    id
    title
    summary @include(if: $withSummary)
  }
}
class GetBookQuery$Book {
  final String id;
  final String title;
  final String? summary; // Nullable due to @include
  
  GetBookQuery$Book({
    required this.id,
    required this.title,
    this.summary, // Optional parameter
  });
}

For unions and interfaces with inline fragments, you need sum types (sealed classes). Consider a search result that returns either books or authors:

query Search($term: String!) {
  search(term: $term) {
    ... on Book {
      __typename
      id
      title
    }
    ... on Author {
      __typename
      id
      name
    }
  }
}

Your generator should produce:

sealed class SearchQuery$SearchResult {}

class SearchQuery$SearchResult$Book extends SearchQuery$SearchResult {
  final String id;
  final String title;
  
  SearchQuery$SearchResult$Book({
    required this.id,
    required this.title,
  });
}

class SearchQuery$SearchResult$Author extends SearchQuery$SearchResult {
  final String id;
  final String name;
  
  SearchQuery$SearchResult$Author({
    required this.id,
    required this.name,
  });
}

Use pattern matching to handle the different types:

void displayResult(SearchQuery$SearchResult result) {
  switch (result) {
    case SearchQuery$SearchResult$Book book:
      print('Book: ${book.title}');
    case SearchQuery$SearchResult$Author author:
      print('Author: ${author.name}');
  }
}

Implementation Strategy

To implement this in your project, you’ll need a code generation tool. While you can build your own, existing packages like graphql_codegen follow this pattern. The key steps are:

  1. Schema-first approach: Start with your GraphQL schema definition
  2. Operation parsing: Analyze each query/mutation to understand exactly what fields are requested
  3. Fragment extraction: Identify and reuse fragment definitions across operations
  4. Type generation: Create Dart classes that match the exact selection set
  5. Data parsing: Deserialize JSON responses into these typed classes

This approach requires more generated code but pays off in developer experience. You get:

  • True null safety based on your actual queries
  • Compile-time errors if you try to access fields you didn’t request
  • Automatic serialization/deserialization
  • Better IDE autocompletion

Common Mistakes to Avoid

  1. Mixing query-specific and shared models: Once you commit to query-specific models, don’t fall back to shared models for “convenience”—it breaks the type safety.

  2. Ignoring fragments: Fragments are essential for reusing type definitions across queries. Use them consistently.

  3. Forgetting __typename: Always include __typename in union/interface selections—it’s needed for proper deserialization.

  4. Manual model creation: Don’t hand-write these models. The complexity grows quickly with nested types and conditional fields.

Conclusion

Embracing query-specific models aligns GraphQL’s flexibility with Dart’s type system. While it generates more classes, the benefits are substantial: you eliminate whole categories of null-related bugs, improve code readability, and leverage Dart’s type system to its full potential. Your widgets become more predictable, your data handling simpler, and your entire codebase more maintainable.

The initial setup requires investment in code generation tooling, but once established, this approach scales beautifully with your GraphQL schema. You get the best of both worlds: GraphQL’s efficiency in fetching only needed data, and Dart’s strong typing to ensure you use that data correctly.

This blog is produced with the assistance of AI by a human editor. Learn more

Related Posts

Cover image for Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.

Cover image for Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.