Skip to content
Skills Library
Programming · Review & audit

dart-code-style

/dart-code-style

Dart code style and naming conventions from Effective Dart — dart format (tall style), lowerCamelCase/UpperCamelCase/snake_case rules, file and library naming, imports ordering, simplicity (no top-level helper functions, no extensions on own types, no speculative abstraction — helpers are private methods on the owning class), double-quoted strings only, dot shorthands for enums and static members (.center, .all(8), .fromSeed), no var (final, const, or an explicit type for mutable variables), type annotations, doc comments (///), private members, getters, cascades, collection literals, and cont

Licence
MIT
Last repository change
05.11.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 05.11.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Dart code style and naming conventions from Effective Dart — dart format (tall style), lowerCamelCase/UpperCamelCase/snake_case rules, file and library naming, imports ordering, simplicity (no top-level helper functions, no extensions on own types, no speculative abstraction — helpers are private methods on the owning class), double-quoted strings only, dot shorthands for enums and static members (.center, .all(8), .fromSeed), no var (final, const, or an explicit type for mutable variables), type annotations, doc comments (///), private members, getters, cascades, collection literals, and cont

Original author description

Dart code style and naming conventions from Effective Dart — dart format (tall style), lowerCamelCase/UpperCamelCase/snake_case rules, file and library naming, imports ordering, simplicity (no top-level helper functions, no extensions on own types, no speculative abstraction — helpers are private methods on the owning class), double-quoted strings only, dot shorthands for enums and static members (.center, .all(8), .fromSeed), no var (final, const, or an explicit type for mutable variables), type annotations, doc comments (///), private members, getters, cascades, collection literals, and cont

How it works

  1. Formatting
  2. Naming
  3. Variables and types
  4. Strings
  5. Idioms
  6. Keep it simple
  7. Dot shorthands (Dart 3.10+)
  8. Control flow: pattern matching over if/else
  9. Imports
  10. Doc comments
Original SKILL.md headings · 313 lines, 2,787 words
SKILL.md preview
---
name: dart-code-style
description: "Dart code style and naming conventions from Effective Dart — dart format (tall style), lowerCamelCase/UpperCamelCase/snake_case rules, file and library naming, imports ordering, simplicity (no top-level helper functions, no extensions on own types, no speculative abstraction — helpers are private methods on the owning class), double-quoted strings only, dot shorthands for enums and static members (.center, .all(8), .fromSeed), no var (final, const, or an explicit type for mutable variables), type annotations, doc comments (///), private members, getters, cascades, collection literals, and control flow with switch expressions, if-case, and guard clauses instead of if/else chains. Use when writing or reviewing Dart/Flutter code, naming things, or settling style questions. Analyzer configuration lives in dart-lint."
license: MIT
metadata:
  author: Matiss Kalnins
  version: "0.5.0"
---

**Persona:** You write Dart that reads like the Dart SDK: formatted by `dart format`, named per Effective Dart, with no ceremony the language doesn't need.

## Formatting

- Always run `dart format .`. Don't hand-format or argue about whitespace. Since Dart 3.7 the formatter uses the "tall" style and manages trailing commas itself, so don't add them by hand to force a layout.
- Line length defaults to 80. Change it for the whole project only, under `formatter: page_width:` in `analysis_options.yaml`, never per file.

## Naming

| Kind | Style | Example |
| --- | --- | --- |
| Classes, enums, typedefs, extensions, type params | `UpperCamelCase` | `UserRepository`, `Result<T>` |
| Variables, functions, params, members, constants, enum values | `lowerCamelCase` | `fetchUser`, `maxRetries`, `Status.active` |
| Files, directories, packages, import prefixes | `snake_case` | `user_repository.dart`, `as http` |

- Constants are `lowerCamelCase` (`const defaultTimeout = Duration(seconds: 10);`), never `SCREAMING_CAPS`.
- Acronyms longer than two letters are capitalized like words: `HttpClient`, `JsonParser`, `userId`. Two-letter acronyms keep both letters together: `IOStream`, `dbId`.
- Booleans read as assertions: `isEmpty`, `hasError`, `canSubmit`. Avoid `getIsEnabled`.
- Methods with side effects are verbs (`save()`, `refresh()`). Cheap, side-effect-free values are getters (`total`), not `getTotal()`.
- Prefer `fooToBar()` for conversions that copy and `asBar()` for views of the same data.
- `_private` means library-private. Don't use a leading underscore on local variables or parameters. Use `_` for parameters you ignore; since Dart 3.7 `_` is a true wildcard and can be repeated: `(_, _) => 0`.

## Variables and types

- **Never use `var`.** Every declaration is one of:
  - `const`: compile-time constants and constant widget constructors.
  - `final`: the default for everything that's never reassigned.
  - **An explicit type**, only when the variable genuinely has to be reassigned: `int retries = 0;`, `String? cursor;`, `late Duration elapsed;`. The written type marks the variable as mutable on purpose, so a reader sees it immediately.
- This applies everywhere `var` could appear:

```dart
// Bad
var count = 0;
var name = user.name;
for (var i = 0; i < n; i++) {}
for (var item in items) {}
var (lat, lng) = parse(input);
var _cache = <String, User>{};

// Good
int count = 0;                       // reassigned below → explicit type
final String name = user.name;       // never reassigned → final, with its type
for (int i = 0; i < n; i++) {}       // loop counter mutates → explicit type
for (final TeamStanding team in ordered) {}
final (double lat, double lng) = parse(input);
```

- Reaching for a mutable typed variable is a signal to reconsider. Most reassignment can become a `final` computed with an expression: a `switch` expression, `fold`, a collection literal, or a helper function.
- **Annotate `final` locals with their type**: `final String fixed = value.toStringAsFixed(3);`, `final Result<PlayerLanding> result = await repo.getPlayer(id);`, `final LeaderCategory category = ref.watch(leadersCategoryProvider);`. There are two exceptions, where the type is already right there or is noisy generated machinery:
  - `ref.watch`/`ref.read` of a repository or an `AsyncValue`: `final repo = ref.watch(playersRepositoryProvider);`, `final leadersState = ref.watch(leadersProvider);`.
  - Constructor calls: `final router = GoRouter(...)`, `final response = await _api.getStandings(day);` when the API method name says it.
- Annotate all public API types (fields, return types, parameters).
- Never write `dynamic` unless you mean "any type, checked at runtime". Prefer `Object?` when you just mean "anything".
- Don't annotate initializing formals: `User(this.name);`.
- Use `required` named parameters for more than two or three arguments, or for any boolean: `Button(onPressed: ..., isPrimary: true)`.

## Strings

- **Always use double quotes**, never single quotes: `"Hello, $name"`, `import "package:flutter/material.dart";`, `part "user.g.dart";`, map keys `json["id"]`. This is enforced by `prefer_double_quotes` (see `dart-lint`).
- The only exception is a literal that contains a double quote itself: `'He said "no"'`. Prefer a triple-quoted string when it's long.
- Use interpolation, not concatenation: `"Total: ${items.length}"`, and `$name` without braces for simple identifiers.
- Use raw strings for regexes and paths with backslashes: `r"\d+"`.

## Idioms

```dart
// Collection literals, spreads, collection-if/for
final List<Widget> items = [
  header,
  if (showBanner) banner,
  for (final u in users) UserTile(user: u),
  ...footers,
];

// Cascades for configuring one object
final paint = Paint()
  ..color = Colors.red
  ..strokeWidth = 2;

// Expression bodies for one-liners
int get count => _items.length;

// Interpolation, not concatenation
"Hello, $name! You have ${items.length} items."
```

- Use `isEmpty` / `isNotEmpty`, not `length == 0`.
- Use `whereType<T>()`, not `where((e) => e is T).cast<T>()`.
- Use tear-offs: `items.forEach(print)`, `onPressed: _submit`. Prefer `for` loops over `forEach` with a closure body.
- Don't use `new`. Don't write `this.` unless it disambiguates.

## Keep it simple

**Write the most direct code that does the job. Every helper, layer, and abstraction has to earn its place.**

- **No top-level helper functions in `lib/`, private or public.** Logic that belongs to a type is a method or getter on that class: a private method (`_fetchStandings()`), a private static method (`static AppFailure _fromDio(...)`), or a getter (`failure.userMessage`, `gameState.isOngoing`). Allowed top-level functions: `main`, Riverpod functional providers, and generated code. Small top-level helpers in **test files** are fine.
- **Shared formatting goes in a static-method class** in `core/formatting/`, not in free functions:

```dart
/// Shared number formats for hockey stats.
abstract final class StatFormat {
  /// Fraction as a percentage with one decimal, e.g. `0.1516` as `15.2%`.
  static String percent(num fraction) {
    return "${(fraction * 100).toStringAsFixed(1)}%";
  }

  /// Seconds as `m:ss`, e.g. `1710` as `28:30`.
  static String minutes(int seconds) {
    final String secs = (seconds % 60).toString().padLeft(2, "0");
    return "${seconds ~/ 60}:$secs";
  }

  /// Adds a leading `+` to positive numbers, e.g. `+23`, `0`, `-4`.
  static String signed(int value) {
    return switch (value) {
      > 0 => "+$value",
      _ => "$value",
    };
  }
}
```

- **Top-level constants are fine** for values shared within a feature: `const int leaderboardLimit = 15;`, `const double leaderRankWidth = 28;`, `const Duration liveRefreshInterval = Duration(seconds: 60);`. Put them next to the code that defines their meaning, with a `///` comment.
- **Local functions are fine** when one function needs a small helper only it uses (the router's `playerDetails` builder).
- **No extensions on your own types.** Put the method in the class (`CartState.add`, `Result.toAsyncValue`). Use extensions only to add behavior to types you don't own, and only when it's used in several places.
- **Inline one-off logic.** A two-line expression used once stays where it's used. Extract a private method only when it names a real step (`_login`, `_freshToken`), is reused, or keeps a method readable.
- **Small, concrete abstractions over layered ones.** The whole data path is Retrofit API → one concrete repository → providers. A repository is the right size of abstraction: it hides the API and returns `Result`s. Abstract repositories with an `Impl`, use cases, data sources, mappers, and one class per operation are not, so don't write them.
- **No speculative abstraction.** No interface with a single implementation (every Dart class is already an implicit interface, so tests `implements` the concrete class), no base classes or wrappers "for later", no generic utilities, and no extra model layers that just copy fields (see `dart-json-serialization`). Add the abstraction when the second real use shows up.
- **Prefer plain language features over machinery.** Use a `switch` instead of a map of callbacks, a method call instead of an event bus, and a field instead of a getter that just returns it.
- **Widgets are the exception:** UI pieces become small widget classes, never `_buildX()` methods (see `flutter-widgets`).

```dart
// Bad: free-floating helpers and an extension on our own type
String _formatPrice(int cents) => "€${(cents / 100).toStringAsFixed(2)}";
extension CartX on CartState {
  String get formattedTotal => _formatPrice(total);
}

// Good: the behavior lives on the class that owns the data
@freezed
class const CartState({final IList<Item> items = const IListConst([])}) with _$CartState {
  int get total => items.fold(0, (sum, i) => sum + i.price);

  String get formattedTotal => "€${(total / 100).toStringAsFixed(2)}";
}
```

## Dot shorthands (Dart 3.10+)

**Use the `.` shorthand wherever the expected type is known.** That covers enum values, static constants and getters, static methods, and named constructors:

```dart
// Bad
Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start);
Padding(padding: const EdgeInsets.fromLTRB(spaceXL, spaceMD, spaceXL, 0));
BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(spaceMD)), border: Border.all(color: ref.outline));
Text(label, style: AppTextStyles.paragraph2, textAlign: TextAlign.center);
if (status == Status.active) { ... }

// Good
Column(mainAxisAlignment: .center, crossAxisAlignment: .start);
Padding(padding: const .fromLTRB(spaceXL, spaceMD, spaceXL, 0));
BoxDecoration(borderRadius: .all(.circular(spaceMD)), border: .all(color: ref.outline));
Text(label, style: AppTextStyles.paragraph2, textAlign: .center);
if (status == .active) { ... }
```

Where the shorthand works:

| Position | Example |
| --- | --- |
| Arguments | `textAlign: .center`, `fit: .cover`, `fontWeight: .bold`, `padding: const .symmetric(horizontal: spaceXL, vertical: spaceMD)` |
| Switch cases and patterns | `case .active:`, `.paid => "Paid"`, `Order(status: .shipped)` |
| The right-hand side of `==` / `!=` | `status == .archived` |
| Return values and `=>` bodies with a declared return type | `Status parse(String s) => .unknown;` |
| Typed declarations and parameter defaults | `final Duration timeout = .zero;`, `[this.stackTrace = .empty]`, `final ProductStatus status = .unknown` |
| Annotations with typed parameters | `@JsonSerializable(fieldRename: .snake)` |
| Static methods and getters of the expected type | `final int n = .parse(raw);`, `width: .infinity` |

Flutter's abstract parameter types forward the common members, so `padding: .all(8)`, `margin: .symmetric(...)`, `alignment: .center`, and `borderRadius: .circular(8)` work even though the parameters are typed `EdgeInsetsGeometry`, `AlignmentGeometry`, and `BorderRadiusGeometry`.

Keep the longhand when:

- **There's no expected type.** `final status = Status.active;` stays longhand. Don't add a type annotation just to use a shorthand.
- **The member lives on a different class than the expected type**: `Colors.red` (expects `Color`), `Icons.add` (expects `IconData`), and `SizedBox.shrink()` where a `Widget` is expected.
- **The parameter is typed `Object`/`Enum`**: `@JsonKey(unknownEnumValue: ProductStatus.unknown)`.
- **It's an unnamed constructor.** Write `Color(0xFF3D5AFE)`, not `.new(0xFF3D5AFE)`. `.new(...)` compiles, but hides which type is being built.

## Control flow: pattern matching over if/else

**Never write `else` or `else if`.** Branching is a `switch` expression (when it produces a value), a `switch` statement (when it runs effects), or an `if (x case pattern)` (when it matches one shape and binds values).

| Instead of | Write |
| --- | --- |
| `if/else if/else` producing a value | a `switch` expression |
| `if/else if` running side effects | a `switch` statement |
| `if (x != null) { use(x) }` | `if (x case final v?) { use(v) }` |
| `if (x is Foo) { x.bar }` | `if (x case Foo(:final bar)) { ... }` |
| Conditions on two or more values | `switch` on a record: `switch ((a, b)) { (true, false) => ... }` |
| `cond ? a : b` on null checks | `x ?? fallback`, or `switch (x) { null => ..., final v => ... }` |
| Nested ternaries | a `switch` expression |
| `asyncValue.when(...)`, `.maybeWhen`, `.map` callbacks on sealed types | a `switch` over the subtypes (`AsyncData`, `AsyncError`, `AsyncLoading`) |
| Ranges and thresholds | relational patterns: `switch (n) { < 0 => ..., 0 => ..., _ => ... }` |

```dart
// Bad (a getter on Order)
String get label {
  if (status == Status.paid) {
    return "Paid";
  } else if (status == Status.shipped && trackingId != null) {
    return "Shipped ($trackingId)";
  } else {
    return "Pending";
  }
}

// Good
String get label => switch (this) {
      Order(status: .paid) => "Paid",
      Order(status: .shipped, :final trackingId?) => "Shipped ($trackingId)",
      _ => "Pending",
    };

// Bad
if (response.statusCode == 200 && body != null) { ... } else if (response.statusCode == 404) { ... } else { ... }

// Good
switch ((response.statusCode, body)) {
  case (200, final b?):
    render(b);
  case (404, _):
    showNotFound();
  case _:
    showError();
}
```

Still allowed:

- **Guard clauses** with an early return and no `else`: `if (!mounted) return;`, `if (items.isEmpty) return const EmptyView();`. Each guard is one exit, not a branch chain. Prefer `if (x case final v?)` when the guard needs to bind a value.
- **Collection `if` without `else`** for optional elements: `[header, if (showBanner) banner]`. When there are two alternatives, use a `switch` expression for the element.
- **A single, flat ternary** between two trivial values on a `bool` (`isSelected ? 2.0 : 1.0`). Anything longer, nested, or null-checking becomes a `switch`.

Exhaustiveness:

- Switch over sealed classes, enums, and `bool` **without** a `_`/`default` case when every case is listed. Then adding a new subtype or enum value is a compile error at every switch that has to handle it.
- Use `_` only when the domain is open (strings, ints, open class hierarchies).
- Use `when` guards for conditions that patterns can't express: `Circle(:final r) when r > 10 => ...`.

## Imports

Order: `dart:` → third-party `package:` → your own app's barrels, each group alphabetized and separated by blank lines.

- Import your own code **only through barrels**, with `package:` imports: `import "package:app/src/core/core.dart";` and `import "package:app/src/leaders/leaders.dart";`. Never import an individual file (`package:app/src/leaders/models/stat_leader.dart`), and never use relative imports (see `flutter-project-layout`).
- The only exceptions are `export` lines inside a barrel and `part` directives, which use relative paths.

## Doc comments

- **Document every public class, provider, repository method, API method, enum value with a non-obvious meaning, and model field with a non-obvious format.** For example: `/// Season as yyyyyyyy, e.g. 20262027.`, or `/// Only set once the game has ended.`
- Use `///` starting with a single-sentence summary that ends with a period. Reference identifiers in square brackets: `Returns the [User] with [id], or null.`
- Document *why* and *contract*, not what the code obviously does. Skip doc comments on overrides unless behavior differs.
- Use `//` for implementation notes. Don't leave commented-out code behind.

## Function bodies

- Use `=>` for one-expression members: getters, providers that build one object, short `switch` expressions.
- Use a block body with `return` once there's a local variable or more than one statement, which includes most `build` methods:

```dart
@override
Widget build(BuildContext context, WidgetRef ref) {
  final String name = "${leader.firstName.value} ${leader.lastName.value}";

  return InkWell(onTap: onTap, child: Text(name, style: AppTextStyles.title3Bold));
}
```

- Separate the setup lines from the `return` with a blank line.

## Immutability (default for every class)

- Classes are immutable unless they wrap a framework-owned mutable object (a controller, a socket, a stream controller). Every field is `final`, constructors are `const` where possible, and hand-written value classes carry `@immutable` from `package:meta`.
- `final` isn't enough for collections. Fields in models and state are `IList`/`ISet`/`IMap` from `fast_immutable_collections`. Use `List.unmodifiable(...)` only at a boundary that requires a plain `List`.
- Models and state classes use **primary constructors** with freezed (`class const Person({required final String name}) with _$Person`). See `dart-json-serialization`.
- Widgets use primary constructors too: `class const PriceRow({super.key, required final String label}) extends StatelessWidget`. State classes (`_PriceRowState`) have no constructor parameters, so they stay plain classes.
- No public setters and no mutating methods on models. "Changing" a value returns a new instance (`copyWith`, or a transition method returning the new value).
- Locals are `final` unless reassigned. Never mutate a collection you received as a parameter. Build a new one.
- A **local** mutable collection is fine while computing a result inside one function, for example a `Map` filled with `putIfAbsent` when grouping. Convert it with `.toIList()` before it leaves the function.
- Use records for small immutable value groupings.

## Class design

- Keep one public class per file when the classes are large. Small related types (a sealed family, a widget and its private state) may share a file.
- Make constructors `const` whenever every field is final and of a const-compatible type.
- Order members as: static fields → instance fields → constructors → overrides → public methods → private methods. For Flutter widgets: fields → constructor → `build` → helpers.
- Override `==` and `hashCode` together, or don't override either. Prefer records or generated equality (freezed, equatable) over hand-written equality.

## Review checklist

- [ ] `dart format --set-exit-if-changed .` passes
- [ ] Names follow the table above; no `SCREAMING_CAPS`, no `get` prefix
- [ ] No `var` anywhere; `final`/`const` by default; mutable variables have an explicit type
- [ ] No `else`/`else if`: switch expressions/statements, `if case`, or guard clauses instead
- [ ] Switches over sealed/enum types are exhaustive without `_`/`default`
- [ ] No top-level helper functions or extensions on own types; logic lives in methods on the owning class
- [ ] No speculative abstractions, wrappers, or copy-only model layers
- [ ] Double-quoted strings only
- [ ] Dot shorthands for enum values, static members, and named constructors wherever the type is known
- [ ] No stray `dynamic`
- [ ] Classes immutable: `final` fields, unmodifiable collections, no setters
- [ ] Public API has `///` docs and explicit types

Versions

The database has no other skills named dart-code-style.

Database snapshot: 13.11.2026 · package version fc375adfee01 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 1 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100effective-dart
    Use when writing Dart code, reviewing for style, refactoring naming, adding doc comments, structuring imports, or enforcing type annotations.
  • 100flutter-dart-style
    Write modern, concise, idiomatic Dart 3.13 / Flutter 3.47 code - primary constructors, private named parameters, dot shorthands, null-aware elements, patterns and sealed classes, records, extension types, widget-class conventions, const, lints (very_good_analysis/flutter_lints),…
  • 100dart-write-documentation
    Rules and formatting guidelines for writing Dart /// API documentation and doc comments. Use when documenting Dart code, writing doc comments for any Dart declaration (libraries, classes, methods, variables, etc.), or when instructed to follow the Effective Dart documentation guidelines.
  • 100refactor-dart-dot-shorthands
    Refactor Dart code to use modern language features, specifically dot shorthands (member access shorthands) introduced in Dart 3.7. Use this when you want to make code more concise by removing redundant type names in enum or static member access when the context type is known.
  • 100naming-conventions
    Enforces Effective-Dart casing (UpperCamelCase types, lowerCamelCase members/constants, lowercase_with_underscores files) plus architectural role suffixes so a name or grep reveals the layer — Screen/Notifier/Repository/Dao/Service/Gateway/Failure, file=primary-declaration,…
  • 100dart-discipline
    Apply Effective Dart guidelines (and the project's `dart-discipline.md`, if installed) whenever Claude touches Dart or Flutter code. Triggers on `.dart` files, `pubspec.yaml`, widgets, pods / blocs / riverpod / signals state, Flutter tests, build runners, or any conversation…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.