
# Flutter Tools

Flutter Tools makes Dart and Flutter work in Zed the way they work in VS Code. It includes everything Zed's own Dart extension gives (highlighting, the Dart language server, its tasks, the `Dart` debugger) and adds what a Flutter developer needs every day: running the app on a device, hot reload on save, DevTools and snippets.

| | |
|---|---|
| Extension id | `flutter-tools` |
| Version | `0.3.0` |
| Needs | Flutter on the `PATH`, or [fvm](https://fvm.app). Nothing else: the extension runs on the Flutter SDK's own Dart |
| Source | [flutter-extension](https://github.com/farum-azula/zed_editor_extensions/tree/main/flutter-extension) in the zed_editor_extensions repository |

Flutter Tools defines the Dart language itself, because only the extension that defines a language can add run tasks to it. It therefore **replaces** Zed's Dart extension: uninstall that one first (see [Installation](installation.md#before-installing-flutter-tools)).

## What it gives

- **Run and debug on every platform.** Zed's run window offers the app on the iOS Simulator, Android, the web, macOS, Windows and Linux, in the terminal or under the debugger. A simulator or emulator is started when none runs. Nothing is written into the project.
- **Hot reload on save, hot restart on Restart**, under the debugger and in the terminal alike.
- **Hot reload for plain Dart programs**, servers and CLIs, including Spring Boot for Dart applications.
- **Flutter DevTools** for the app under the debugger, in a window next to Zed. Selecting a widget opens its code in Zed.
- **`build_runner watch`** started in the background for projects that use it.
- **144 snippets** with short prefixes, each adding the imports it needs.
- **Code in documentation comments, highlighted** as Dart (or Java, Rust, JavaScript, TypeScript, Python).
- **A newer Dart grammar** that parses Dart 3.12 and 3.13 syntax, such as primary constructors (`class A({required this.x})`).
- **Semantic token rules** for Dart, so fields, annotations and closure parameters keep sensible colours when semantic highlighting is on.

## Running the app

Open the run window from a Dart file: `task: spawn` for the **Run** tab, `debugger: start` (`F4` in the default keymap) for the **Debug** tab. For each platform there is a pair:

| Tab | Name | What it is |
|---|---|---|
| Run | `Flutter: run on iOS Simulator` | `flutter run` in the terminal, with `r`, `R` and `q` |
| Debug | `Flutter: debug on iOS Simulator` | The debugger, with hot reload on save and hot restart |

The same pair exists for Android, Web, macOS, Windows and Linux. The run button in the gutter next to a Flutter app's `main()` offers the run tasks too. Each task picks its device by platform:

| Platform | Device |
|---|---|
| iOS Simulator | A running simulator; otherwise an iPhone simulator of the newest iOS is booted |
| Android | A connected phone or a running emulator; otherwise the first emulator is started |
| Web | Chrome or Edge; without either, `web-server`, whose URL opens in any browser |
| macOS, Windows, Linux | This computer, each only on its own OS |

They run `lib/main.dart` of the project root, through fvm when the project has a `.fvmrc`. For a flavor, another entry point or one particular phone, add a scenario of your own (see [Debug options](#debug-options)).

The Run tab also lists `flutter run`, `fvm flutter run`, `flutter test`, `fvm flutter test`, `dart pub get`, `dart analyze`, `dart format`, `dart run build_runner build` and `dart run build_runner watch`.

### Plain Dart

For a project that is not a Flutter app, `task: spawn` offers:

| Task | What it runs |
|---|---|
| `dart run: <file>` | `dart run` for the file open in the editor, in its package; builds first when the project uses `build_runner`. Also on the run button next to `main()` |
| `dart run: bin/main.dart` | `dart run bin/main.dart` in the project root; builds first when the project uses `build_runner` |
| `dart test` | `dart test` for the whole project (`flutter test` for a Flutter app) |

The Debug tab has no ready-made Dart scenario yet, but the `Dart` debug adapter is there. A scenario in the project's `.zed/debug.json` debugs a Dart program:

```json
{
  "label": "Dart: bin/main.dart",
  "adapter": "Dart",
  "type": "dart",
  "request": "launch",
  "program": "bin/main.dart"
}
```

## Hot reload and hot restart

**In a `Flutter: run on ...` task**, saving a `.dart` file under the app's `lib/` hot reloads it. Several saves within 200 ms make one reload. The runner gives `flutter run` a `--pid-file` and sends it `SIGUSR1`, Flutter's own signal for a hot reload, so the terminal stays Flutter's and `r`, `R` and `q` work as usual. When `build_runner watch` rewrites a `.dart` file under `lib/`, the app reloads too. Not on Windows, which has no such signals: press `r` there.

**In a `dart run: <file>` task** (a server or CLI on the Dart VM), the program runs with its VM service on. Saving a `.dart` file of its package, or a file under `lib/resources/`, hot reloads it, and the terminal shows a line like:

```text
↻ Reloaded in 55 ms
```

A Spring Boot for Dart application (`spring_boot_dart` 0.3.2 and later) then restarts itself when its beans, annotations or config files changed, such as a new `@GetMapping` or another `server.port`, and keeps running with the new method bodies otherwise, like Spring Boot DevTools. See [Hot reload](../../components/spring-boot-starter-flutter/hot-reload.md) for the Flutter side. A compile error is shown only when the code still does not compile 2 seconds later, so stale generated code is not reported. `Ctrl+C` stops the program.

**Under the debugger** (a `Flutter: debug on ...` scenario, or one of your own for the `Flutter` adapter):

| What you do | What happens |
|---|---|
| Save a `.dart` file under `lib/` | Hot reload: the new code runs, the app keeps its state |
| **Restart** in the debug panel | Hot restart: the app starts over, without a rebuild |
| **Stop** | The app quits |

Breakpoints, stepping, variables and the debug console are Flutter's own debugger's. With autosave on (`"autosave": {"after_delay": {"milliseconds": 1000}}`), the app reloads a second after you stop typing.

Extensions cannot add key bindings. For a hot restart from the keyboard, add this to your keymap (`zed: open keymap file`). It saves the file, then restarts the app:

```json
[
  {
    "context": "Editor",
    "bindings": {
      "cmd-alt-s": ["action::Sequence", ["workspace::Save", "debugger::Restart"]],
      "ctrl-alt-s": ["action::Sequence", ["workspace::Save", "debugger::Restart"]]
    }
  }
]
```

### Debug options

A scenario of your own for the `Flutter` adapter, in the project's `.zed/debug.json`:

```json
{
  "label": "Flutter: Android (dev)",
  "adapter": "Flutter",
  "request": "launch",
  "program": "lib/main_dev.dart",
  "target": "android",
  "toolArgs": ["--flavor", "dev"]
}
```

| Field | Default | Meaning |
|---|---|---|
| `target` | none | `ios-simulator`, `android`, `web`, `macos`, `windows`, `linux`: a device of that kind, chosen as above |
| `deviceId` | Flutter's choice | One device by id (`flutter devices`); wins over `target` |
| `program` | `lib/main.dart` | The entry point, relative to `cwd` |
| `cwd` | the project root | The Flutter project's folder (in a monorepo, the app's folder) |
| `flutterMode` | `debug` | `debug`, `profile` or `release`; reload and restart need `debug` |
| `args` | `[]` | Arguments for the app |
| `toolArgs` | `[]` | Arguments for `flutter run`: `--flavor dev`, `--dart-define=K=V` |
| `env` | `{}` | Environment variables for Flutter |
| `hotReloadOnSave` | `true` | `false` reloads only on Restart |
| `devTools` | `true` | `false`: no DevTools for this app |
| `useFvm` | `true` with a `.fvmrc`, else `false` | Run Flutter through fvm |
| `request` | `launch` | `attach`, with `vmServiceUri`, attaches to a running app |

## Flutter DevTools

DevTools works with an app running under the debugger:

1. Start the app in the **Debug** tab: `Flutter: debug on <platform>`.
2. Open DevTools from the **Run** tab with one of these tasks:

| Task | Shows |
|---|---|
| `Flutter DevTools: Widget Inspector` | The live widget tree, with each widget's properties and layout |
| `Flutter DevTools: Performance` | Frame times, jank, rebuilds and the timeline |
| `Flutter DevTools: CPU Profiler` | Where the time goes, by function |
| `Flutter DevTools: Memory` | The heap, allocations and leaks |
| `Flutter DevTools: Network` | HTTP requests and their responses |
| `Flutter DevTools: Logging` | Logs, `log()` calls included, and framework events |

The page opens in a window of its own next to Zed: Chrome, Edge or Chromium in app mode (no tabs, no address bar), or the default browser. Every page is a tab of that window, so one task is enough to reach all of them. The debug console prints DevTools' address too.

**Selecting a widget opens its code in Zed**: a click in the inspector's tree, or a tap on the widget in the app with *Select Widget Mode* on. This needs Zed's command line tool, `zed`: on macOS run `cli: install` from the command palette; elsewhere it must be on the `PATH`.

DevTools is a web app, and a Zed extension cannot show web pages or draw panels of its own. Until Zed can, DevTools lives in a window next to it.

## build_runner in the background

When a project has `build_runner` in the `dev_dependencies` of its `pubspec.yaml` (the workspace folder and the packages below it, down to 4 levels, such as `example/flutter_app` in a monorepo), the extension's language server starts `dart run build_runner watch --delete-conflicting-outputs` there once, when the project opens. It stops the watch when Zed closes the server.

In a pub workspace (build_runner 2.14 and later) one watch builds every member. The watch starts again when a `pubspec.yaml`, `pubspec.lock` or `.dart_tool/package_config.json` changes. Another build_runner command, such as a `build` by hand, asks the watch for its lock; a watch that still holds it after 30 seconds is restarted, so the command never waits for ever.

Each `Succeeded` or `Failed` line of a build is shown as a message in Zed. The full output is in `dev: open language server logs`, under `flutter-tools`.

## Snippets

Type a prefix and pick the snippet from the completion menu. The menu shows only the snippets that start with what is typed, and nothing after `{`, `(` or `.`. `Ctrl-Space` lists them all. `Tab` moves to the next field; a field that appears more than once is edited everywhere at once; fields with a fixed set of values (`MainAxisAlignment.start`, `BoxFit.cover`) offer them as a list. With the defaults, the code compiles once the names it refers to exist.

Prefixes are mostly the first letters of the words: `sfp` is a **s**tate**f**ul widget with a **p**arameter, `lvb` a **L**ist**V**iew.**b**uilder, `ftb` a **F**u**t**ure**B**uilder.

Picking a snippet also **adds the imports it needs** when the file has none that brings them. Typing `ftb` in a file without imports inserts:

```dart
FutureBuilder<String>(
  future: future,
  builder: (context, snapshot) {
    if (snapshot.hasError) {
      return Text('${snapshot.error}');
    }
    if (!snapshot.hasData) {
      return const Center(child: CircularProgressIndicator());
    }
    final data = snapshot.requireData;
    return Text('$data');
  },
)
```

and adds `import 'package:flutter/material.dart';` at the top. That is why the snippets come from the extension's language server rather than from a Zed snippet file: Zed's snippets can only insert at the cursor.

The Dart language server has snippets of its own, so these do not repeat them: `stless`, `stful`, `stanim`, `class`, `main`, `fun`, `for`, `forin`, `if`, `ife`, `switch`, `try`, `while`, `do`, `test`, `group`.

### Logging and async

| Prefix | Inserts | Import |
|---|---|---|
| `log` | `log()`, shown in the debug console and DevTools | `dart:developer` |
| `loge` | `log()` of an error with its stack trace | `dart:developer` |
| `logd` | `debugPrint()`, printed in debug builds only | `flutter/foundation.dart` |
| `pr` | `print()` | |
| `tm` | Start a Timer | `dart:async` |
| `tmp` | Start a periodic Timer | `dart:async` |
| `cpl` | Create a Completer | `dart:async` |
| `sctrl` | A broadcast StreamController field | `dart:async` |

### App and widget classes

| Prefix | Inserts |
|---|---|
| `mapp` | A MaterialApp with a home screen |
| `capp` | A CupertinoApp with a home screen |
| `mna` | `main()` that initializes bindings before `runApp` |
| `thd` | A Material 3 ThemeData from a seed color |
| `slc` | A StatelessWidget that wraps a child |
| `sfp` | A StatefulWidget with a field read through `widget.` |
| `inh` | An InheritedWidget with `of()` and `maybeOf()` |
| `cn` | A ChangeNotifier with one notifying field |
| `cpt` | A CustomPainter |
| `ccl` | A `CustomClipper<Path>` |

### State members

| Prefix | Inserts |
|---|---|
| `ins`, `ds`, `dcd`, `duw`, `dea`, `bld` | Override `initState`, `dispose`, `didChangeDependencies`, `didUpdateWidget`, `deactivate`, `build` |
| `ac` | An AnimationController (the State needs a TickerProvider mixin) |
| `tc`, `sc`, `fn` | A TextEditingController, a ScrollController, a FocusNode |
| `fk` | A `GlobalKey<FormState>` |
| `gt`, `st` | A getter, a setter |

### Statements

| Prefix | Inserts |
|---|---|
| `ss` | Call setState |
| `ifm`, `ifcm` | Stop when the State, or the BuildContext, is no longer mounted (after an await) |
| `np`, `npn`, `npr`, `npa` | Push a MaterialPageRoute, push a named route, replace the route, push and remove all others |
| `npo`, `npu` | Pop the current route, pop back to the first route |
| `sd` | Show an AlertDialog with cancel and confirm actions |
| `sbs` | Show a modal bottom sheet |
| `ssb` | Show a SnackBar through the ScaffoldMessenger |
| `pfc` | Run code after the current frame |
| `fd` | Wait for a duration |
| `tcf` | try with catch and finally |
| `uf` | Dismiss the keyboard |
| `ifc` | Match a pattern |
| `fid` | Loop over a list with its indexes |

### Layout

| Prefix | Inserts |
|---|---|
| `scf` | A Scaffold with an AppBar |
| `ab` | An AppBar with actions |
| `col`, `row`, `stk`, `pos` | A Column, a Row, a Stack, a Positioned child |
| `cen`, `al` | A Center, an Align |
| `pd`, `pds` | Padding on all sides, horizontal and vertical padding |
| `sbh`, `sbw`, `sbx` | Vertical space, horizontal space, a SizedBox with a child |
| `ct`, `dct` | A Container, a Container with a rounded BoxDecoration |
| `ex`, `fx` | An Expanded, a Flexible |
| `wr`, `sa` | A Wrap, a SafeArea |
| `crr` | Clip with rounded corners |
| `cd`, `lt`, `dv` | A Card with padding, a ListTile, a Divider |
| `cpi` | A centered progress indicator |
| `vis` | Show a child conditionally |

### Scrolling

| Prefix | Inserts |
|---|---|
| `lv`, `lvb`, `lvs` | A ListView of children, lazily built, with separators |
| `gvb`, `gvc` | A lazily built grid, a grid of children, with a fixed column count |
| `scv` | A scrollable Column |
| `csv` | A CustomScrollView with an app bar and a list |
| `slb`, `sla`, `slp` | A lazily built sliver list, a box widget in a CustomScrollView, padding around a sliver |
| `ri` | Pull to refresh |
| `pvb` | A lazily built PageView |
| `dtc` | A DefaultTabController with a TabBar and a TabBarView |

### Builders

| Prefix | Inserts |
|---|---|
| `bd` | A Builder for a new BuildContext |
| `lb` | Build from the parent constraints |
| `ftb`, `stb` | Build from a Future, from a Stream, with loading and error states |
| `vlb`, `lnb`, `anb` | Rebuild when a ValueListenable changes, when a Listenable notifies, on every animation tick |

### Content, input and animation

| Prefix | Inserts |
|---|---|
| `tx`, `rt` | A Text with a theme style, text with several styles |
| `ic` | An Icon |
| `img`, `imgn` | An image from the assets, from the network with loading and error states |
| `hr` | A Hero animation |
| `gd`, `iw` | Detect taps, a tappable area with a ripple |
| `eb`, `flb`, `ob`, `tb`, `ib`, `fab` | Elevated, Filled, Outlined, Text, Icon and FloatingAction buttons |
| `tf`, `tff`, `frm` | A TextField with a controller, a TextFormField with a validator, a Form with a submit button |
| `cbt`, `swt`, `sl`, `dd` | A checkbox with a label, a switch with a label, a Slider, a DropdownButton |
| `anc`, `ano`, `ans` | A Container that animates its changes, fade a child in and out, animate between children |

### Theme, Dart and tests

| Prefix | Inserts |
|---|---|
| `mqs`, `th`, `tt`, `cs` | The size of the screen, the theme, the text theme, the color scheme |
| `imm`, `imc`, `imw`, `ims`, `ima` | Import material, cupertino, widgets, services, `dart:async` |
| `mdl` | An immutable class with copyWith, JSON, equality and toString |
| `en`, `sld`, `ext`, `mx` | An enum with a field, a sealed class with two subclasses, an extension, a mixin |
| `sgl`, `td` | A class with a single instance, a type alias |
| `fa`, `fs` | A function returning a Future, a function generating a Stream |
| `todo` | A TODO comment |
| `tw` | A widget test |
| `su`, `tdn`, `sua` | Run before each test, after each test, once before all tests |
| `tp`, `et`, `ef` | Tap a widget and settle, type into a text field, expect a widget to be found |

## Code in documentation comments

The fenced code blocks of `///` comments are highlighted as code; the rest of the comment stays a comment:

````dart
/// Returns the basket's total.
///
/// ```dart
/// final total = basket.total(); // highlighted as Dart
/// ```
double total() => ...
````

A fence with no language counts as Dart, as dartdoc reads it. Fences named `java`, `rust`, `javascript`, `typescript` and `python` are highlighted in that language; Java needs Zed's Java extension installed. Other languages stay comments. The examples get their own styles (`keyword.dartdoc` and so on), so a theme can set them apart: the [Farum Azula Themes](themes.md) show them in darkened colours. An example's classes stay out of the outline and its `main()` gets no run button.

## Configuration

| Setting | Where | Effect |
|---|---|---|
| `"lsp": { "flutter-tools": { "initialization_options": { "build_runner": false } } }` | Zed `settings.json` | No background `build_runner watch` |
| `FLUTTER_TOOLS_BUILD_RUNNER=off` | Zed's environment | The same |
| `FLUTTER_TOOLS_HOT_RELOAD_ON_SAVE=off` | Zed's environment | No hot reload on save in the run tasks; `dart run:` tasks use plain `dart run` |
| `FLUTTER_TOOLS_BUILD_RUNNER_YIELD_MS` | Zed's environment | How long a watch may keep the build lock after another command asks for it; 30000 by default |
| `"lsp": { "dart": ... }` | Zed `settings.json` | Settings of the Dart language server, as with Zed's Dart extension |

To semantic-highlight Dart, set `"languages": { "Dart": { "semantic_tokens": "combined" } }`. The extension's rules then let the tree-sitter colours show for annotations and declared variables, colour a field named in a constructor (`this._scope`) as a field, and colour a closure's parameters with `variable.parameter.closure` when the [Spring for Dart](spring-for-dart.md) extension is installed.

## Troubleshooting

**Installation fails, or Dart is defined twice.** Zed's Dart extension is still installed. Uninstall it on the Extensions page and remove `"dart": true` from `auto_install_extensions` if it is there.

**`Flutter: debug on <platform>` is missing from the Debug tab.** After you have run `Flutter: run on <platform>`, Zed leaves that scenario out of the list until it restarts. The other platforms stay.

**A DevTools task opens nothing.** It needs an app started from the Debug tab. An app started with `Flutter: run on ...` has no DevTools here; `flutter run` prints a DevTools link in its terminal instead.

**Selecting a widget does not open the file.** Install Zed's command line tool: `cli: install` on macOS, or put `zed` on the `PATH`.

**No hot reload on save on Windows in a run task.** Windows has no `SIGUSR1`; press `r` in the terminal, or use the Debug tab.

**"Waiting for already-running build_runner".** The background watch holds the lock; it gives it up within 30 seconds. To turn the watch off, see [Configuration](#configuration).

## Links

- [Source of the extension](https://github.com/farum-azula/zed_editor_extensions/tree/main/flutter-extension)
- [The snippets](https://github.com/farum-azula/zed_editor_extensions/blob/main/flutter-extension/tool/snippets.json)
- [Zed's Dart extension](https://github.com/zed-extensions/dart), which this one includes
- [Installation](installation.md)
