Google Integrates AI Agents with Flutter DevTools to Automate Testing

How to write really good Flutter code — Flutter

Flutter

Standardizing code architecture through the Model Context Protocol allows AI agents to perform complex debugging and testing tasks without hallucination.

AI-assisted summary of How to write really good Flutter code — original source. Check the original for full context.

Source published:

Key ideas

  • The Flutter team advocates for a seven-technique framework to enhance code quality, focusing on constraints-based layout, architectural separation, and automated testing. (0:45)
  • The integration of Model Context Protocol (MCP) servers allows AI coding agents to access real-time Flutter DevTools and up-to-date documentation, significantly reducing hallucination risks. (2:38)
  • Maintaining a strict separation of concerns via the MVVM (Model-View-ViewModel) pattern and Repository pattern ensures data sources are isolated and testable. (7:48)
  • Flutter's new `checks` package provides a more robust, strongly typed alternative to the traditional `matcher` package for unit testing. (12:08)

Detailed notes

## Background This session, titled 'How to write really good Flutter code', was published by the Flutter YouTube channel on May 21, 2026. The content serves as a guide to writing high-quality, maintainable Flutter applications, highlighting the integration of modern tooling like Widget Previews, DevTools, and AI-powered MCP server skills.

## TL;DR The presentation outlines seven practical engineering principles for building scalable and testable Flutter apps, using a demo e-commerce app called the Dash Shop as a case study. The speakers demonstrate how to implement responsive layouts, utilize the MVVM architecture, and enforce the Repository pattern to decouple logic from presentation. Additionally, they show how AI agents can assist developers by leveraging Flutter-specific skills and real-time documentation through the Model Context Protocol (MCP). The session concludes by emphasizing a rigorous, multi-tiered testing strategy to ensure long-term application stability.

## Atmosphere & style The tone is professional, collaborative, and highly practical, mirroring the clear-cut, instructional style of a Google I/O developer session. There is a palpable sense of forward-looking optimism as the speakers—Mariam Hasnany, Eric Windmill, and John Ryan—balance traditional software engineering rigor with the excitement of AI-assisted workflows. The dynamic between them is fluid and supportive, creating an atmosphere that feels like an encouraging, expert-led workshop designed to make complex architectural concepts feel approachable and attainable.

## Bulletin - [00:45](https://www.youtube.com/watch?v=O0UjId1VoRU&t=45s) The Flutter team advocates for a seven-technique framework to enhance code quality, focusing on constraints-based layout, architectural separation, and automated testing. - [02:38](https://www.youtube.com/watch?v=O0UjId1VoRU&t=158s) The integration of Model Context Protocol (MCP) servers allows AI coding agents to access real-time Flutter DevTools and up-to-date documentation, significantly reducing hallucination risks. - [07:48](https://www.youtube.com/watch?v=O0UjId1VoRU&t=468s) Maintaining a strict separation of concerns via the MVVM (Model-View-ViewModel) pattern and Repository pattern ensures data sources are isolated and testable. - [12:08](https://www.youtube.com/watch?v=O0UjId1VoRU&t=728s) Flutter's new `checks` package provides a more robust, strongly typed alternative to the traditional `matcher` package for unit testing.

## Key takeaways - [00:45](https://www.youtube.com/watch?v=O0UjId1VoRU&t=45s) Responsive layout design should follow a three-stage methodology: abstracting data, measuring constraints, and branching UI widgets. - [00:45](https://www.youtube.com/watch?v=O0UjId1VoRU&t=45s) Developers should avoid fixed sizes; using `LayoutBuilder` and `MediaQuery` ensures widgets are resilient across different screen form factors. - [02:38](https://www.youtube.com/watch?v=O0UjId1VoRU&t=158s) Flutter DevTools should be used for diagnosing layout overflow issues instead of relying on trial-and-error manual adjustments. - [02:38](https://www.youtube.com/watch?v=O0UjId1VoRU&t=158s) The Dart and Flutter MCP server allows AI assistants to ingest raw runtime errors and control the inspector to resolve layout bugs automatically. - [04:30](https://www.youtube.com/watch?v=O0UjId1VoRU&t=270s) Reusable widgets must be decoupled from business logic; they should only display data and forward interactions through callbacks. - [04:30](https://www.youtube.com/watch?v=O0UjId1VoRU&t=270s) Widget Previews enable testing components in isolation across different visual states without needing to launch the entire application. - [06:14](https://www.youtube.com/watch?v=O0UjId1VoRU&t=374s) Flutter-official AI agent skills are validated using a public evals framework at `github.com/flutter/evals` to ensure model reliability. - [07:48](https://www.youtube.com/watch?v=O0UjId1VoRU&t=468s) MVVM architecture acts as a gatekeeper, where ViewModels transform domain models for UI consumption while delegating mutations to the data layer. - [07:48](https://www.youtube.com/watch?v=O0UjId1VoRU&t=468s) ViewModels should extend `ChangeNotifier` to notify the UI of state changes without directly executing data persistence logic. - [09:19](https://www.youtube.com/watch?v=O0UjId1VoRU&t=559s) The Repository pattern establishes a single source of truth and encapsulates data source implementation, whether local or remote. - [09:19](https://www.youtube.com/watch?v=O0UjId1VoRU&t=559s) Repositories significantly improve testability by allowing developers to swap real implementations for mock objects during unit tests. - [10:13](https://www.youtube.com/watch?v=O0UjId1VoRU&t=613s) MCP integration allows AI agents to perform real-time searches of `pub.dev` documentation, ensuring code uses current API versions. - [12:08](https://www.youtube.com/watch?v=O0UjId1VoRU&t=728s) Testing is tiered into three levels: unit tests for isolated functions, widget tests for UI components, and integration tests for complete user journeys. - [12:08](https://www.youtube.com/watch?v=O0UjId1VoRU&t=728s) The `checks` package improves the unit testing experience by providing strong typing and superior IDE integration over the legacy `matcher` package. - [12:08](https://www.youtube.com/watch?v=O0UjId1VoRU&t=728s) AI agents can be utilized to automate the migration of existing test suites from `matcher` to the newer `checks` package. - [12:08](https://www.youtube.com/watch?v=O0UjId1VoRU&t=728s) Flutter integration tests can be recorded and generated by AI agents using the Flutter Driver to reproduce user interaction sequences.

## Detailed walkthrough ### [00:00](https://www.youtube.com/watch?v=O0UjId1VoRU&t=0s) Seven Techniques for High-Quality Flutter Code

Mariam Hasnany opens the session alongside Eric Windmill and John Ryan to walk through practical engineering principles for creating readable, scalable, and testable Flutter applications. Rather than discussing abstract theory, the team grounds their recommendations in a concrete demo application called the Dash Shop—an exclusive e-commerce storefront offering Dash-themed merchandise ranging from plush stuffies to custom mechanical keyboards.

Throughout the presentation, the speakers examine the architectural foundation of the app’s checkout flow while demonstrating how modern developer workflows combine classical software engineering patterns with assistive artificial intelligence. As Eric Windmill emphasizes, the goal is long-term stability: “These techniques will help you build your Flutter app with a scalable and maintainable app architecture so it can go the distance.” John Ryan adds that tooling and AI agents can seamlessly assist developers throughout the implementation cycle when codebases follow these structured conventions.

[00:45](https://www.youtube.com/watch?v=O0UjId1VoRU&t=45s) Technique 1: Design Using Constraints, Not Fixed Sizes

When building multiplatform applications, Flutter enables a single codebase to run across mobile, desktop, and web screen form factors. However, cross-platform adaptability demands careful layout discipline. Mariam warns against hardcoded, fixed dimensions, quipping: “With ease comes responsibility, as a wise bird once told me.” Designing with constraints ensures widgets remain flexible, reusable, and resilient against unexpected screen dimensions.

Eric breaks down responsive layout design into a three-stage methodology: abstract, measure, and branch. While standard flex widgets such as `Row`, `Column`, and `Flex` accommodate proportional resizing, drastic layout shifts are required when a screen becomes too cramped or leaves excessive unused whitespace.

```mermaid flowchart LR accTitle: Responsive Layout Strategy accDescr: Three-step process showing Abstracting data, Measuring constraints, and Branching UI widgets. A["Abstract Data<br/>(Pass via constructor)"] --> B["Measure Display<br/>(LayoutBuilder / MediaQuery)"] B --> C["Branch Layout<br/>(Return adaptive widgets)"] ```

To implement this technique: - **Abstract**: Isolate shared data from presentation logic. In the Dash Shop cart screen, data required for rendering is passed purely as constructor parameters. As Eric Windmill points out: “The widget shouldn't care about where the data comes from, just that it needs to display it.” - **Measure**: Evaluate available viewport dimensions. Use `MediaQuery.sizeOf(context)` when inspecting the full application window, or drop in a `LayoutBuilder` to determine localized constraints for reusable nested components. - **Branch**: Evaluate incoming box constraints provided by `LayoutBuilder` and conditionally return completely different widget hierarchies tailored for compact, medium, or expanded viewports.

[02:38](https://www.youtube.com/watch?v=O0UjId1VoRU&t=158s) Technique 2: Diagnose and Resolve Layouts with DevTools and MCP

Layout bugs frequently lead developers into frustrating trial-and-error cycles. Mariam illustrates the common anti-pattern where an engineer repeatedly tweaks a container's height, hot reloads, tweaks it again, and reloads once more. Instead of guessing, developers should use Flutter DevTools to gain direct visibility into the exact layout constraints enforced by parent widgets.

To demonstrate, John modifies the checkout cart inside the Antigravity editor to enlarge text and product images for accessibility. Triggering a hot reload immediately triggers the classic yellow-and-black striped layout overflow exception. By opening the Flutter DevTools Inspector, the offending `Row` widget is highlighted immediately.

```mermaid flowchart TD accTitle: AI Debugging with Flutter MCP Server accDescr: Architecture connecting Antigravity AI Agent to Flutter DevTools via MCP Server. subgraph IDE["Antigravity Editor"] Agent["AI Assistant (Gemini)"] MCP["Dart & Flutter MCP Server"] end subgraph App["Running Flutter App"] DT["DevTools Inspector"] RT["Runtime & Widget Tree"] end Agent <-->|"Queries errors & controls"| MCP MCP <-->|"Get Runtime Errors / Hot Reload"| DT DT <--> RT ```

Rather than troubleshooting manually, John leverages the Dart and Flutter Model Context Protocol (MCP) server: - As John Ryan explains: “The MCP server makes Flutter's developer tools available to AI assistants.” - The MCP server is installed directly from the Antigravity agent panel by searching under additional server options for Dart. - Once connected to a live running application, the assistant invokes tools like `Get Runtime Errors` to ingest raw layout diagnostics. - Because layout overflow stack traces contain rich structural context that models like Gemini excel at interpreting, the agent inspects the layout tree, applies the fix, triggers hot reload, and calls `Get Widget Tree` to verify that the overflow has been resolved.

[04:30](https://www.youtube.com/watch?v=O0UjId1VoRU&t=270s) Technique 3: Build Reusable Widgets and Leverage Widget Previews

A frequent pitfall in UI development is tangling business logic with rendering code, resulting in deeply nested, unmaintainable `build()` methods. Mariam stresses that separating business logic from interface presentation is essential for maintainability: “By separating your business logic from your UI, your widgets become easier to reuse, modify, and test.”

Eric outlines the strict boundaries of a truly reusable widget: its only responsibilities are displaying received configuration data and forwarding user interactions back up the tree. It should never perform data formatting, initiate HTTP calls, or talk to local databases: - “As a rule of thumb, if your widget is importing low-level libraries, making remote requests, or interacting with the database, it's probably not reusable,” warns Eric Windmill. - In the Dash Shop cart, clicking the "Purchase" button does not directly trigger payment APIs inside the widget; instead, the action is passed upward through an `onPurchase` callback parameter defined on the widget constructor.

Pure, decoupled widgets unlock developer tools such as Widget Previews. Complementing hot reload, Widget Previews allows engineers to view and interact with isolated components across diverse visual states without launching the entire application, logging in, or navigating to nested screens. To streamline preview authoring, the Flutter team provides an official agent skill—`flutter:add-widget-previews`—instructing AI assistants on how to automatically generate preview catalogs for components.

[06:14](https://www.youtube.com/watch?v=O0UjId1VoRU&t=374s) Grounding AI Skills and Validating with Public Evals

John explains that coding agent skills authored by the Flutter team are distributed via their official skills repository on GitHub. These skills translate human best practices into repeatable, structured instructions for AI coding assistants. Each skill includes explicit metadata descriptions so agents only ingest instructions when actively relevant to the current coding task.

To avoid model hallucinations and out-of-date patterns, skills are tightly grounded in Flutter's official documentation as the ultimate source of truth. Mariam notes that releasing AI skills requires the same software engineering rigor applied to framework code: “We've rigorously validated it with our evals framework to ensure it consistently works across use cases.”

- **Continuous Validation**: As foundation models evolve and MCP tools update, the team monitors whether AI-generated code meets quality benchmarks across realistic developer scenarios. - **Open-Source Transparency**: The evaluation harnesses and benchmark suites are developed publicly at `github.com/flutter/evals`, allowing the community to inspect, reproduce, and build upon their evaluation pipelines. - **Widget Cataloging**: Applying the verified preview skill enables agents to generate consistent widget catalogs, ensuring comprehensive UI coverage across light, dark, and localized states.

[07:48](https://www.youtube.com/watch?v=O0UjId1VoRU&t=468s) Technique 4: Bake a Layer Cake with MVVM Architecture

Moving from individual UI components to system design, Mariam introduces layered application architecture under the metaphor of baking a layer cake. Structuring apps through layered patterns like Model-View-ViewModel (MVVM) provides clear separation of concerns across three distinct tiers: the UI layer, the logic layer, and the data layer.

Within MVVM, views (widgets) handle rendering, while ViewModels manage presentation state and user actions. Describing this architectural boundary, Mariam Hasnany notes: “Viewmodels act as a gatekeeper between the UI and the data layer.”

```mermaid flowchart TD accTitle: MVVM Layered Architecture accDescr: Flow diagram showing UI View passing actions to ViewModel, which updates ChangeNotifier and delegates to Data Layer. subgraph UILayer["UI Layer (View)"] CartView["Cart Screen Widget"] end subgraph LogicLayer["Logic Layer (ViewModel)"] CartVM["CartViewModel<br/>(ChangeNotifier)"] end subgraph DataLayer["Data Layer"] Repo["Data Repository"] end

CartView -->|"Invokes callbacks (onPurchase)"| CartVM CartVM -->|"Notifies listeners / updates state"| CartView CartVM -->|"Delegates persistence / mutation"| Repo ```

Eric elaborates on the three explicit responsibilities assigned to a ViewModel: 1. Transforming domain models into data structures ready for UI consumption (e.g., computing a formatted `subtotal` from `cartItems`). 2. Instructing the data layer when user actions require mutations. 3. Notifying the UI when internal state changes occur by extending Flutter’s built-in `ChangeNotifier`.

In the Dash Shop implementation, when a customer taps "Purchase," the `CartViewModel` immediately toggles an internal `isLoading` flag and calls `notifyListeners()`, which causes the cart screen to display a progress indicator. However, the ViewModel never executes payment transactions directly; it delegates data persistence and mutation downstream to the underlying data layer.

[09:19](https://www.youtube.com/watch?v=O0UjId1VoRU&t=559s) Technique 5: Centralize Access with the Repository Pattern

Handling external network connections, database transactions, and hardware plugins directly within state management code creates brittle dependencies. Mariam introduces the Repository pattern as the fifth technique to centralize and abstract data access. Repositories sit firmly inside the data layer, mediating between external endpoints and the ViewModels.

Eric emphasizes that a repository enforces strict data boundaries: “This pattern is used to establish a single source of truth per data source in your app and should be the only object that can fetch from or write data to an external source.”

Key architectural guarantees of the Repository pattern include: - **Single Source of Truth**: Consolidates read and write operations for a specific domain model into a unified contract, preventing conflicting data across screens. - **Encapsulated Data Sources**: Hides whether information originates from an in-memory cache, local SQLite database, or remote REST/gRPC backend. - **Enhanced Testability**: Allows unit tests to swap concrete network implementations with mock repositories without modifying ViewModel or UI logic. - **AI-Assisted Architecture**: Developers can apply these patterns using the official Flutter architecture skill published on GitHub, configuring their coding agents to structure application layers automatically.

### [10:13](https://www.youtube.com/watch?v=O0UjId1VoRU&t=613s) Managing Platform-Specific Features with MCP The speakers transition into the challenge of cross-platform development, specifically when data layers must interact with native platform features like payment systems. While Flutter is built on Dart, functionality on Android and iOS often requires interfacing with Kotlin and Swift APIs. John Ryan explains that the vast ecosystem of plugins on pub.dev simplifies this by abstracting implementation details, allowing developers to maintain consistent Dart code across platforms.

John demonstrates how a coding agent, paired with an MCP (Model Context Protocol) server, streamlines the search for these packages. By asking the agent to implement a checkout experience using Apple Pay and Google Pay, the MCP server allows the agent to search pub.dev in real-time and pull current documentation directly into the workspace. John notes, “Because the MCP server searched the package docs, the code correctly uses the latest API version rather than relying on training data.” This approach ensures that the generated code is accurate and up-to-date.

- **MCP Benefits:** Enables real-time searching of package documentation and provides the agent with workspace-specific context to generate better, more reliable code. - **Workflow:** If the agent’s suggestion is not ideal, developers can reject the changes and provide further context to refine the output.

### [12:08](https://www.youtube.com/watch?v=O0UjId1VoRU&t=728s) The Importance of Testing Mariam Hasnany introduces testing as the seventh essential technique, describing it as the necessary "vegetables" of the development process that ensures long-term reliability. John outlines a three-tiered testing strategy, noting that a well-architected app makes this process significantly easier.

The testing approach is broken down as follows: * **Unit Tests:** John emphasizes that these are for validating individual classes or functions in isolation. He highlights the new `checks` package, which provides strong typing and IDE integration compared to the traditional `matcher` package. He mentions there is even an agent "skill" available to automate the migration from `matcher` to `checks`. * **Widget Tests:** These verify Flutter UI components without needing a physical device or emulator, allowing for rapid execution while still interacting with the UI. * **Integration Tests:** These verify the complete user journey on a real device. John shows how an agent, equipped with a dedicated "Flutter integration testing skill," can interact with the app via Flutter Driver to record steps and generate a reproducible test script.

“With the checks package, everything is strongly typed, so your IDE knows which checks are valid for the data type you're testing,” says John Ryan, underscoring the developer experience improvements in the testing workflow.

### [14:30](https://www.youtube.com/watch?v=O0UjId1VoRU&t=870s) Recap and Best Practices The session concludes with a summary of the seven techniques discussed for writing high-quality Flutter code. Mariam and John reiterate that whether developers are coding manually or using AI assistance, these principles remain the foundation for scalable and maintainable applications.

```mermaid flowchart TD subgraph Techniques A["Design for constraints"] B["Debug with DevTools"] C["Reusable widgets"] D["Layered architecture"] E["Repository pattern"] F["Multi-platform design"] G["Comprehensive testing"] end

A --> B B --> C C --> D D --> E E --> F F --> G

accDescr: A summary of the seven core principles for Flutter development presented in the session. ```

The speakers emphasize that these tools—from the MCP server to testing skills—are designed to make code more "readable, scalable, testable, and faster than ever." They direct the audience to flutter.dev for further documentation and best practices.

## Notable quotes > [00:45](https://www.youtube.com/watch?v=O0UjId1VoRU&t=45s) The widget shouldn't care about where the data comes from, just that it needs to display it. — Eric Windmill

> [04:30](https://www.youtube.com/watch?v=O0UjId1VoRU&t=270s) By separating your business logic from your UI, your widgets become easier to reuse, modify, and test. — Mariam Hasnany

> [10:13](https://www.youtube.com/watch?v=O0UjId1VoRU&t=613s) Because the MCP server searched the package docs, the code correctly uses the latest API version rather than relying on training data. — John Ryan

> [09:19](https://www.youtube.com/watch?v=O0UjId1VoRU&t=559s) This pattern is used to establish a single source of truth per data source in your app and should be the only object that can fetch from or write data to an external source. — Eric Windmill

> [07:48](https://www.youtube.com/watch?v=O0UjId1VoRU&t=468s) Viewmodels act as a gatekeeper between the UI and the data layer. — Mariam Hasnany

## Mentioned Flutter, Google I/O 2026, Mariam Hasnany, Eric Windmill, John Ryan, Dash Shop, Gemini, Dart, Flutter DevTools, Model Context Protocol (MCP), Antigravity editor, pub.dev, Android, iOS, Apple Pay, Google Pay, SQLite

## Video description Explore the principles of writing high-quality, maintainable Flutter code, and how tooling like Widget Previews, DevTools, MCP server and Skills make it easier than ever to write high-quality code.

Resources: Flutter Evals Docs → https://goo.gle/4uvFN6X Flutter Evals GitHub → https://goo.gle/4uvnlLM Flutter Skills GitHub → https://goo.gle/4uPSdXB Flutter Docs - Create with AI → https://goo.gle/42hY23B

Watch the Flutter sessions from Google I/O 2026 → https://goo.gle/Flutter-at-IO26 Watch the cloud sessions from Google I/O 2026 → https://goo.gle/Cloud-at-IO2026

Subscribe to Flutter → http://goo.gle/FlutterYT

#GoogleIO

Speakers: Mariam Hasnany, Eric Windmill, John Ryan Event: Google I/O 2026 Products Mentioned: Cloud, Flutter, Mobile

[Source](https://www.youtube.com/watch?v=O0UjId1VoRU)

Reading summary

Flutter engineers Mariam Hasnany, Eric Windmill, and John Ryan present seven engineering practices that pair classical software architecture with assistive AI tooling to build maintainable, multiplatform applications. Constraint-Based Layouts and Decoupled Widgets (0:45) Cross-platform development requires responsive layout discipline rather than hardcoded dimensions. Eric Windmill outlines a three-step responsive methodology—abstract, measure, and branch—where shared data is isolated via constructor arguments, viewport constraints are measured with tools like LayoutBuilder or MediaQuery, and conditional widget hierarchies adapt to screen size. To ensure component reusability, Windmill cautions that widgets should only render passed data and emit user actions via callbacks, avoiding direct database operations, network calls, or low-level library imports. Decoupling presentation logic simplifies testing and enables Widget Previews, allowing developers to inspect isolated visual states across themes and localizations without launching the entire application. Layered Architecture Using MVVM and Repositories (7:48) System design in Flutter benefits from a layered Model-View-ViewModel (MVVM) structure that separates interface rendering, business logic, and data handling. Under this pattern, the View handles UI display, while the ViewModel acts as a gatekeeper that transforms raw domain data for presentation, triggers state updates via ChangeNotifier, and requests mutations from underlying layers without performing transactions directly. To manage external inputs, the Repository pattern establishes a single source of truth for each domain data source. Windmill explains that repositories abstract whether data originates from an in-memory cache, local database, or remote network API. This architectural boundary centralizes read and write logic while allowing engineers to substitute mock repositories seamlessly during unit testing. AI Tooling with DevTools and MCP (2:38) Instead of relying on manual trial-and-error to debug layout overflow errors, developers can connect AI coding assistants directly to Flutter DevTools using the Dart and Flutter Model Context Protocol (MCP) server. John Ryan demonstrates that an MCP-enabled agent in an editor can read runtime error diagnostics, inspect layout constraints, modify widget code, execute hot reloads, and check the updated widget tree to verify fixes. To ensure AI reliability, the Flutter team provides structured coding skills grounded in official documentation rather than generic training data. Hasnany notes that these skills undergo continuous testing through the open-source flutter/evals framework on GitHub, validating that model-generated code meets engineering standards across evolving foundation models and tool interfaces. Platform Integration and Three-Tiered Testing (12:08) Handling native platform features like Apple Pay or Google Pay requires coordinating Dart code with platform-specific Swift and Kotlin plugins. Using the MCP server, AI assistants can query pub.dev in real time to locate packages and integrate up-to-date APIs directly into the workspace rather than relying on stale model training data. For quality assurance, Ryan outlines a three-tiered testing hierarchy: strongly typed unit tests using the modern checks package instead of the traditional matcher library, widget tests for verifying UI components without an emulator, and full-device integration tests driven by test-generation skills and Flutter Driver. Adhering to decoupled architectures ensures components at each level remain isolated and testable. The presenters emphasize that structured architectural boundaries—such as pure widgets, MVVM, and repositories—are prerequisites for maximizing the utility of automated testing and assistive AI tools across cross-platform Flutter codebases.

Source quotes

[0:45] Eric Windmill: The widget shouldn't care about where the data comes from, just that it needs to display it. [4:30] Mariam Hasnany: By separating your business logic from your UI, your widgets become easier to reuse, modify, and test. [10:13] John Ryan: Because the MCP server searched the package docs, the code correctly uses the latest API version rather than relying on training data. [9:19] Eric Windmill: This pattern is used to establish a single source of truth per data source in your app and should be the only object that can fetch from or write data to an external source. [7:48] Mariam Hasnany: Viewmodels act as a gatekeeper between the UI and the data layer.

Original transcript

[0:00] [MUSIC PLAYING] [0:06] MARIAM HASNANY: Hi. [0:06] I'm Mariam, a Product Manager for Flutter. [0:09] Today, we're going to share seven tools and techniques you [0:11] can use right now to make your Flutter code more readable, [0:15] scalable, and testable. [0:17] I'm joined by Eric and John, who will help me demonstrate [0:20] these techniques to build a checkout experience in our Dash [0:22] shop app, an exclusive online store for Dash gear-- stuffies, [0:26] keyboards, you name it. [0:28] ERIC WINDMILL: These techniques will help you build your Flutter [0:30] app with a scalable and maintainable app architecture [0:34] so it can go the distance. [0:36] JOHN RYAN: And we'll also share some tools [0:38] that you can use to add features to your app and some cool ways [0:41] that AI can use them to Assist you. [0:43] [MUSIC PLAYING] [0:45] MARIAM HASNANY: All right, let's dive into the code. [0:47] The first technique is all about building [0:49] a great UI, design using constraints and not fixed sizes. [0:54] Flutter makes it possible for us to have the Dash [0:56] store available on any device and any screen [0:59] with a single code base. [1:01] But with ease comes responsibility, [1:04] as a wise bird once told me. [1:06] It's our job as developers to ensure [1:08] the UI is visually responsive while keeping the code readable [1:12] and error free. [1:14] Designing using constraints makes your widgets [1:16] flexible and more reasonable than if they [1:18] were using fixed sizes. [1:20] That way, you can easily reuse them for mobile, desktop, [1:24] or the web. [1:25] Essentially, that boils down to three steps-- abstract, measure, [1:29] and branch. [1:30] ERIC WINDMILL: The UI currently uses Flutter's flex layout [1:33] with widgets like row, column, and flex [1:36] to help make sure the widgets resize based [1:38] on the size of the constraints. [1:40] But when the screen gets too small to display everything [1:43] or so large that there's wasted screen space, [1:46] you need to swap out the layout with an entirely different one [1:49] appropriate for the screen size. [1:51] So the first step is to identify the UI widgets that [1:54] need to change and abstract the underlying data they share. [1:58] In this case, the card screen layout [2:00] needs to change based on the screen size. [2:02] We'll pass the data it needs to render in [2:05] via the constructor parameter. [2:07] The widget shouldn't care about where the data comes from, just [2:10] that it needs to display it. [2:12] Next, let's measure the size of your display area. [2:16] Use MediaQuery.sizeOf for the entire app window [2:19] or LayoutBuilder for the localized constraints. [2:22] Since this is a smaller widget that we want to reuse, [2:24] we'll use LayoutBuilder. [2:26] Finally, we can read the incoming constraints [2:29] that LayoutBuilder gives us and return different widgets [2:31] based on the available size. [2:34] To learn more, check out the layout docs [2:36] linked in the description. [2:38] MARIAM HASNANY: If our UI layout is broken, or the app freezes, [2:41] we could fiddle with the height of the container, [2:44] hot reload, fiddle with the height again, hot reload again. [2:48] Or we could save some time and skip all of the guesswork [2:52] by using DevTools to provide visibility [2:55] into the app, such as the exact constraints that the parent [2:58] widget is enforcing. [3:00] Our second technique is use DevTools. [3:03] Keeping accessibility in mind, let's make [3:05] the images and the text in the checkout cart [3:08] bigger so that they are more visible. [3:11] JOHN RYAN: Let's see. [3:12] That should be pretty easy. [3:14] I'll open up Antigravity and enter a prompt [3:16] with the widget I want to change. [3:18] OK, so Antigravity made the change. [3:21] Now I'll tell it to reload. [3:23] And we hit a classic issue, the dreaded layout overflow error. [3:28] To help us understand what's going on, [3:30] let's use DevTools to see which widget is causing the error. [3:34] The Flutter DevTools Inspector highlights these errors [3:37] so we can see which widget is causing the issue-- [3:40] this row widget, which is overflowing. [3:43] We can dig into the details ourselves, [3:45] or we can use the Dart and Flutter MCP server [3:47] to help us fix the issue. [3:49] The MCP server makes Flutter's developer tools [3:51] available to AI assistants. [3:55] To install it in Antigravity, we'll open up the agent panel [3:58] and select MCP servers under the additional options dropdown [4:01] menu and search for Dart. [4:04] Once installed, Antigravity displays the available tools. [4:08] When we run our app, our agent can connect to it directly. [4:12] And once it's connected, the agent [4:14] can read the layout error message using the Get Runtime [4:17] Errors tool. [4:19] Layout errors contain a lot of details [4:20] that Gemini is really good at understanding. [4:24] The agent knows how to use the hot reload [4:26] and Get Widget Tree Tools to help make sure [4:28] that it fixed the layout error. [4:30] MARIAM HASNANY: Mixing business logic and UI within a widget [4:33] creates massive, unreadable, deeply nested build methods. [4:37] By separating your business logic from your UI, [4:40] your widgets become easier to reuse, modify, and test. [4:45] So technique 3 is building reusable widgets. [4:49] ERIC WINDMILL: As mentioned before, [4:50] a widget should receive all the configuration it [4:52] needs to render as arguments. [4:55] It shouldn't have to modify or format any data. [4:57] It's only jobs are to render data and listen for user events. [5:02] As a rule of thumb, if your widget [5:04] is importing low-level libraries, [5:06] making remote requests, or interacting with the database, [5:09] it's probably not reusable. [5:11] In the Dash store app, when a user presses Purchase, [5:14] the widget doesn't turn around and call the payments API [5:17] directly. [5:18] So in order to keep the widget reusable [5:20] and only focused on displaying the UI, [5:22] that logic is deferred to a different object using [5:25] a callback that is passed in as a parameter [5:28] to the widget's constructor. [5:31] When your widgets are reusable, you [5:32] can leverage tools like widget previews. [5:35] Widget previews is a developer tool [5:37] that complements hot reload, enabling you to experiment [5:40] with UI variations in states without running [5:42] the full application. [5:44] Rather than running an app, navigating to a specific screen, [5:48] and getting the app into a specific state [5:50] just to test button styles, I can write some widget previews [5:53] for that button and pass them in, [5:55] enabling me to quickly iterate on designs. [5:58] This is straightforward, since our widgets were [6:00] built to be reusable, and if you're [6:02] building with AI assistance, the Flutter team [6:04] has published a skill, Flutter ad widget previews, [6:08] that gives instructions to your coding [6:09] agents on how to build previews for your app's widget catalog. [6:14] JOHN RYAN: This skill is published [6:15] as part of Flutter's official skills repository on GitHub, [6:19] and it provides instructions for agents [6:21] that can be shared and repeated to reliably complete [6:23] a task for you. [6:25] We authored this skill by grounding it [6:27] in our official documentation. [6:29] This means that the skills are up to date [6:31] and keeps our official docs as the source of truth. [6:35] Each skill has a name and description [6:36] that tell the agent what it should be used for [6:39] and when to use it. [6:40] The agent reads it in only when it's [6:42] relevant to what you're trying to do. [6:44] You can find skills published by the Dart and Flutter [6:46] team on GitHub, so you can start using them for your own projects [6:50] today. [6:50] MARIAM HASNANY: But we didn't just write the skill [6:52] and call it a day. [6:53] We've rigorously validated it with our evals framework [6:56] to ensure it consistently works across use cases. [7:01] Our goal is to consistently deliver [7:02] tools to developers that help you build better apps. [7:06] And with AI's rapid innovation, we [7:08] want to make sure that each skill, MCP tool, and model [7:11] change is making your apps better. [7:13] So we're looking for ways to be more data-driven. [7:16] In fact, we're experimenting with evals in public so the code [7:20] is open source, and you can check it out [7:22] at github.com/flutter/evals. [7:26] JOHN RYAN: So now you can see that we have a widget [7:28] preview for our widget. [7:30] Previews let you test widgets in their various states [7:32] and see how they look when placed next to each other. [7:35] And we can use our skill to create previews for all [7:38] of our important widgets. [7:40] So our widgets are looking good. [7:42] But now we want to start using them in our app, [7:44] and for that, we need to talk about app architecture. [7:47] [MUSIC PLAYING] [7:48] MARIAM HASNANY: Separation of concerns [7:50] is one of the core fundamentals of software development. [7:53] In app development, this generally [7:54] manifests as a layered architecture. [7:57] So the fourth technique is to bake a layer cake. [8:01] We layer our apps using MVVM architecture. [8:04] All MV-something patterns have a similar layered architecture [8:07] using three objects that are roughly equivalent from pattern [8:10] to pattern-- a UI layer, a logic layer, and a data layer. [8:15] In MVVM, your UI is separated into views, [8:19] which are your widgets, and your logic is in the viewmodels. [8:23] Viewmodels act as a gatekeeper between the UI and the data [8:26] layer. [8:26] This separation of logic and UI makes your code [8:29] testable and more readable. [8:32] ERIC WINDMILL: Viewmodels have three jobs-- [8:34] transforming app data into data that's ready to be rendered, [8:37] telling the data layer when user interaction requires [8:40] app data to be modified, and telling the UI when to rebuild. [8:44] And for that, we use change notifier. [8:47] In the Dash store app, the cart viewmodel provides configuration [8:50] for the cart screen and has properties like cart items [8:53] and subtotal and methods called add to cart and on purchase. [8:58] On purchase is the callback referenced earlier [9:00] that we pass into the widget. [9:03] When a user presses the Purchase button, [9:05] the viewmodel handles the local state, things like toggling, [9:08] is loading, and calling notify listeners. [9:11] But it defers the data mutation logic [9:13] to another layer of the proverbial cake, the data layer. [9:17] MARIAM HASNANY: Which brings us to our next technique, [9:19] using the repository pattern. [9:22] The repository pattern centralizes and abstracts [9:25] data access logic. [9:26] And it does so using objects called repositories. [9:30] A repository manages the data in the data layer. [9:33] It's the interface between your app [9:35] and external data like server, database, or plugin. [9:39] Specifically, in our case, it exposes raw data [9:42] from services to the viewmodel. [9:44] ERIC WINDMILL: This pattern is used [9:45] to establish a single source of truth per data source [9:48] in your app and should be the only object that [9:51] can fetch from or write data to an external source. [9:56] When application data logic is isolated in this way, [9:59] it makes your entire code base easier to test and scale. [10:02] If you want to try out these architecture [10:04] techniques in your own apps, use the official architecture skill [10:08] published by the Flutter team to make your AI agent an expert. [10:11] MARIAM HASNANY: The sixth technique [10:13] is to design for all platforms. [10:16] What happens to your data layer when [10:17] you need to use native features, like payments? [10:20] Flutter uses Dart, but platforms like Android and iOS [10:23] expose these features using Kotlin and Swift APIs. [10:27] Thankfully, Flutter enables developers [10:29] to leverage native device features and third-party APIs [10:33] through its massive ecosystem of plugins and packages on pub.dev. [10:38] The huge win for developers is that plugins [10:40] enable us to write Dart code that works consistently [10:43] across all platforms. [10:45] And the implementation details are abstracted away [10:47] as a package on pub.dev. [10:50] JOHN RYAN: Traditionally, to find the right plugin [10:52] for payments, I'd leave my IDE, open a browser, [10:56] hunt down the right package on pub.dev, [10:58] and read through the documentation. [11:00] But did you know that your coding agent [11:02] can help you with that, too? [11:04] Let me show you. [11:06] I've got my Dart and Flutter MCP server ready. [11:08] So let's ask something, "Help me implement a checkout experience [11:12] that uses Apple Pay and Google Pay." [11:16] The agent identifies the official pay package. [11:18] And as you can see here, it's using the MCP server [11:21] to securely interact with external data sources. [11:25] In this case, the MCP server enables our agent [11:28] to search pub.dev in real time, fetch the latest package [11:31] documentation, and analyze the current workspace. [11:34] This makes a big difference because including [11:36] more context helps the agent write correct code. [11:40] If we look at the results, the agent also wrote in the code [11:43] to support Apple Pay and Google Pay in our checkout experience. [11:47] Of course, if we don't what the agent chose for us, [11:50] we can reject the change and provide it with more context. [11:53] Because the MCP server searched the package docs, [11:57] the code correctly uses the latest API version [12:00] rather than relying on training data. [12:03] Here's what the checkout experience [12:04] looks like on Android and iOS. [12:08] MARIAM HASNANY: The new checkout experience is working great. [12:10] But now we need to make sure it keeps working reliably. [12:14] It's a good idea to add automated tests so we [12:17] can know when something breaks. [12:19] No matter how much we don't want to do it, [12:21] our seventh technique is to write tests. [12:24] JOHN RYAN: We've already eaten our vegetables [12:25] and designed our app using good architecture patterns, [12:28] so it's going to be much easier to add tests. [12:32] First, let's add a unit test. [12:34] Unit tests can validate the behavior of Dart code [12:37] very quickly in parallel. [12:39] They're great for testing individual classes or functions [12:42] with different inputs to make sure they work correctly [12:44] in isolation. [12:46] Let's take a look at the cart viewmodel [12:48] to see how we can write a test for it. [12:51] I can see that it takes a dependency as a parameter, [12:53] so we'll want to mock that. [12:55] And we'll use the new checks package like this. [12:59] You might currently be using the matcher package [13:02] to write test expectations like equals or is greater than. [13:06] With the checks package, everything is strongly typed, [13:09] so your IDE knows which checks are valid for the data [13:12] type you're testing. [13:14] We also have an agent skill to help [13:16] you migrate from the matcher package to the checks package. [13:19] Widget tests are great for testing-- [13:22] you guessed it-- Flutter widgets. [13:25] They also run quickly because they [13:26] run without a physical device or an emulator [13:29] and can tap on widgets, verify the text that's on screen, [13:32] and a lot more. [13:35] Here's what the widget test for our button looks like. [13:37] We can verify that it shows the correct values when we tap. [13:41] Finally, let's use an integration test [13:44] to verify that this feature works correctly [13:45] on a physical device. [13:48] Integration tests actually use the same API as widget tests, [13:51] so you don't have to learn a new testing framework. [13:54] And thanks to our MCP server, our coding agent [13:57] can help with this too. [13:59] Let me show you how that works. [14:01] We've created this Flutter integration testing skill [14:04] to help write integration tests. [14:06] First, it enables Flutter Driver, [14:08] which enables the agent to interact with our app. [14:11] From there, it runs the app and interacts with it [14:14] to go through the user journey that we're [14:15] testing on a real device. [14:18] Finally, it captures those steps into an integration test [14:21] that we can reliably run. [14:23] Now, our integration tests can be [14:25] maintained alongside the rest of our test suite. [14:27] [MUSIC PLAYING] [14:30] MARIAM HASNANY: So let's recap. [14:31] We covered seven techniques for writing really good Flutter [14:34] code-- [14:35] designed for constraints, not fixed sizes, [14:38] debug using DevTools, build reusable widgets, [14:42] bake a layer cake, use a repository pattern, [14:45] design for all platforms, and write good tests. [14:49] Whether you're writing out code by hand [14:51] or iterating with your coding agent, [14:53] we hope this helps you write Flutter code that [14:55] is more readable, scalable, testable, and faster than ever. [14:59] To learn more about Flutter's best practices [15:01] and all of our developer tools, point your browser [15:04] to flutter.dev. [15:04] [MUSIC PLAYING]