К основному содержанию
скилл CX Codex

effective-dart — скилл для Claude Code: что делает и как установить

Скилл effective-dart задаёт правила чистого кода на Dart и Flutter: стиль имён, явные типы, оформление документации и структуру тестов.

MIT ★ 674 обновлён 2026-10-29

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add evanca/flutter-ai-rules
/plugin install flutter-ai-skills@flutter-ai-rules
Открыть на GitHub

Что делает effective-dart

Скилл инструктирует ассистента писать код по стандарту Effective Dart. В правилах собраны требования к именованию сущностей, явным аннотациям типов и модификаторам классов вроде sealed или final. Отдельно оговорены исключения: акронимы длиннее двух букв пишутся как слова (HttpRequest), а имена булевых флагов формулируются утвердительно.

Правила диктуют структуру проекта: публичные интерфейсы минимизируются, а файлы делятся по зонам ответственности. Для форматирования скилл предписывает вызывать стандартный dart format, поэтому ручные переносы строк агент не изобретает. Импорты внутри пакета остаются относительными, а вызовы чужих файлов из каталога src запрещены.

Какие задачи решает

  • оформить имена классов, файлов и параметров по правилам Effective Dart
  • расставить модификаторы классов вроде sealed и final для изоляции API
  • структурировать относительные импорты без прямых путей в src чужих пакетов
  • составить понятные doc-комментарии с разметкой идентификаторов через квадратные скобки

Примеры запросов агенту

  • Проверь этот файл с моделями на соответствие правилам Effective Dart
  • Сделай рефакторинг класса AppConfig, добавь явные типы и сделай его final
  • Напиши doc-комментарии для публичных методов в cart_service.dart

Как установить effective-dart

1Через маркетплейс плагинов

/plugin marketplace add evanca/flutter-ai-rules
/plugin install flutter-ai-skills@flutter-ai-rules

Команда ставит плагин flutter-ai-skills целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add evanca/flutter-ai-rules --skill effective-dart -a claude-code

3Вручную: положить файлы

~/.claude/skills/effective-dart/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/effective-dart/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об effective-dart

Как установить effective-dart в Claude Code?

Выполните в терминале агента команду /plugin marketplace add evanca/flutter-ai-rules, а затем /plugin install flutter-ai-skills@flutter-ai-rules. Также скилл можно добавить через команду npx skills add evanca/flutter-ai-rules --skill effective-dart -a claude-code.

Что контролирует скилл effective-dart?

Он задаёт соглашения о типах, модификаторах классов, форматировании через dart format и оформлении документации в ///. Также скилл запрещает импортировать внутренние файлы из папки src сторонних пакетов.

Как скилл требует оформлять doc-комментарии?

Комментарии оформляются через тройной слэш ///, начинаются с отдельного предложения-резюме и ссылаются на идентификаторы через квадратные скобки вроде [identifier].

Исходный текст

SKILL.md · MIT
---
name: effective-dart
description: "Use when writing Dart code, reviewing for style, refactoring naming, adding doc comments, structuring imports, or enforcing type annotations."
license: MIT
---

# Effective Dart Skill

This skill defines how to write idiomatic, high-quality Dart and Flutter code following Effective Dart guidelines.

---

## 1. Naming Conventions

| Kind | Convention | Example |
|---|---|---|
| Classes, enums, typedefs, type parameters, extensions | `UpperCamelCase` | `MyWidget`, `UserState` |
| Packages, directories, source files | `lowercase_with_underscores` | `user_profile.dart` |
| Import prefixes | `lowercase_with_underscores` | `import '...' as my_prefix;` |
| Variables, parameters, named parameters, functions | `lowerCamelCase` | `userName`, `fetchData()` |

- Capitalize acronyms and abbreviations longer than two letters like words: `HttpRequest`, not `HTTPRequest`.
- Avoid abbreviations unless the abbreviation is more common than the full term.
- Prefer putting the **most descriptive noun last** in names.
- Use terms **consistently** throughout your code.
- Follow mnemonic conventions for type parameters: `E` (element), `K`/`V` (key/value), `T`/`S`/`U` (generic types).
- Consider making code **read like a sentence** when designing APIs.
- Prefer a **noun phrase** for non-boolean properties or variables.
- Prefer a **non-imperative verb phrase** for boolean properties or variables; prefer the positive form.
- Consider omitting the verb for named boolean parameters.
- Avoid starting a function or method name with `get`; prefer removing `get` and using a getter when the API conceptually exposes a property.

---

## 2. Types and Functions

- Use **class modifiers** (`final`, `sealed`, `interface`, `base`, `mixin`) to control whether a class can be extended or implemented.
- **Type annotate variables** without initializers.
- Type annotate **fields and top-level variables** if the type isn't obvious.
- **Annotate return types** on function declarations.
- **Annotate parameter types** on function declarations.
- Write **type arguments** on generic invocations that aren't inferred.
- Annotate with `dynamic` instead of letting inference fail.
- Use `Future<void>` as the return type of async members that do not produce values.
- Use **getters** for operations that conceptually access properties.
- Use **setters** for operations that conceptually change properties.
- Use a **function declaration** to bind a function to a name.
- Use **inclusive start and exclusive end** parameters to accept a range.
- Don't annotate a **return type on a setter** — including the `[]=` operator, which behaves like a setter.

```dart
// Prefer: explicit class modifier
final class AppConfig {
  final String apiUrl;
  final int timeout;
  const AppConfig({required this.apiUrl, required this.timeout});
}

// Prefer: sealed for exhaustive pattern matching
sealed class Result<T> {}
class Success<T> extends Result<T> { final T value; Success(this.value); }
class Failure<T> extends Result<T> { final Exception error; Failure(this.error); }
```

---

## 3. Style

```bash
dart format .
```

- Format code with `dart format` — don't manually format.
- Use **curly braces** for all flow control statements.
- Prefer `final` over `var` when variable values won't change.
- Use `const` for compile-time constants.
- Prefer lines **80 characters or fewer** for readability.

---

## 4. Imports and Files

- Don't import libraries inside the `src` directory of another package.
- Don't allow import paths to reach into or out of `lib`.
- **Prefer relative import paths** within a package.
- Don't use `/lib/` or `../` in import paths.
- Consider writing a **library-level doc comment** for library files.

---

## 5. Structure

- Keep files **focused on a single responsibility**.
- Limit file length to maintain readability.
- Group related functionality together.
- Prefer making fields and top-level variables `final`.
- Consider making constructors `const` if the class supports it.
- **Prefer making declarations private** — only expose what's necessary.

---

## 6. Usage Patterns

```dart
// Adjacent string concatenation (not +)
final greeting = 'Hello, '
    'world!';

// Collection literals
final list = [1, 2, 3];
final map = {'key': 'value'};

// Initializing formals
class Point {
  final double x, y;
  Point(this.x, this.y);
}

// Empty constructor body
class Empty {
  Empty();  // not Empty() {}
}

// rethrow to preserve stack trace
try {
  doSomething();
} catch (e) {
  log(e);
  rethrow;
}
```

- Use `whereType<T>()` to filter a collection by type.
- Follow a **consistent rule** for `var` and `final` on local variables.
- Initialize fields at their **declaration** when possible.
- Override `hashCode` if you override `==`; ensure `==` obeys mathematical equality rules.
- **Prefer specific exception handling**: use `on SomeException catch (e)` instead of broad `catch (e)` or `.catchError` handlers.

---

## 7. Documentation

```dart
/// Returns the sum of [a] and [b].
///
/// Throws [ArgumentError] if either value is negative.
int add(int a, int b) { ... }
```

- Format comments like sentences (capitalize, end with period).
- Use `///` doc comments — not `/* */` block comments — for types and members.
- Prefer writing doc comments for **public APIs**; consider them for private APIs too.
- Start doc comments with a **single-sentence summary**, separated into its own paragraph.
- Avoid redundancy with the surrounding context.
- Start function/method comments with a **third-person verb** if the main purpose is a side effect.
- Start with a **noun or non-imperative verb phrase** if returning a value is the primary purpose.
- Start **boolean** variable/property comments with "Whether" followed by a noun or gerund phrase.
- Use `[identifier]` in doc comments to refer to in-scope identifiers.
- Use **prose** to explain parameters, return values, and exceptions (e.g., "The [param]", "Returns", "Throws" sections).
- Put doc comments **before** metadata annotations.
- Document **why** code exists or how it should be used, not just what it does.

---

## 8. Testing Patterns

- Write **unit tests** for business logic, using `group` and descriptive `test` names:

```dart
import 'package:test/test.dart';

void main() {
  group('CartService', () {
    late CartService cart;

    setUp(() => cart = CartService());

    test('addItem increases item count', () {
      cart.addItem(Product(id: '1', name: 'Widget', price: 9.99));
      expect(cart.items, hasLength(1));
    });

    test('removeItem decreases total price', () {
      final product = Product(id: '1', name: 'Widget', price: 9.99);
      cart.addItem(product);
      cart.removeItem(product.id);
      expect(cart.totalPrice, equals(0.0));
    });
  });
}
```

- Write **widget tests** using `testWidgets` and `WidgetTester`:

```dart
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('LoginButton shows loading indicator when tapped',
      (WidgetTester tester) async {
    await tester.pumpWidget(const MaterialApp(home: LoginScreen()));
    await tester.tap(find.byType(ElevatedButton));
    await tester.pump();
    expect(find.byType(CircularProgressIndicator), findsOneWidget);
  });
}
```

---

## 9. Code Review Workflow

When reviewing Dart code for Effective Dart compliance, the agent should check:

1. **Naming** — verify all identifiers follow the conventions in Section 1.
2. **Type annotations** — confirm public API parameters, return types, and uninitialized variables are annotated.
3. **Class modifiers** — verify `final`, `sealed`, or `interface` is used where appropriate.
4. **Documentation** — confirm all public members have `///` doc comments with a single-sentence summary.
5. **Style** — run `dart format --output=none --set-exit-if-changed .` to verify formatting.
6. **Analysis** — run `dart analyze` and confirm zero issues.

---

## References

- [Effective Dart](https://dart.dev/effective-dart)
- [Dart Site WWW GitHub Repository](https://github.com/dart-lang/site-www)

© Ivanna Kaceviča · MIT · evanca/flutter-ai-rules

Похожие скиллы

Все скиллы по теме «Языки программирования» →
dart-best-practices kevmoo Скилл dart-best-practices задаёт правила оформления кода на Dart при генерации и ревью. Помогает форматировать многострочные блоки и соблюдать лимит длины строки в 80 знаков. CX Codex +1 847установок dart-run-static-analysis dart-lang Скилл dart-run-static-analysis запускает dart analyze для поиска ошибок и dart fix --apply для автоисправления предупреждений линтера. Помогает проверять качество кода на Dart перед коммитами. CX Codex +1 21 200установок flutter-dart-code-review affaan-m Скилл flutter-dart-code-review для Claude Code даёт чек-лист ревью Flutter/Dart-кода по виджетам, состоянию, идиомам, производительности и безопасности. CX Codex +1 6 600установок dart-add-unit-test dart-lang Скилл dart-add-unit-test для Claude Code, Codex и других агентов пишет и организует юнит-тесты на package:test. Включается при добавлении логики или исправлении багов, чтобы избежать регрессий. CX Codex +1 21 400установок dart-use-primary-constructors flutter Скилл dart-use-primary-constructors учит агента переводить классы Dart на первичные конструкторы и синтаксис Dart 3.13+. Он пригодится при рефакторинге моделей данных и сокращении шаблонного кода. CX Codex +1 17 000установок dart-flutter-patterns affaan-m Скилл dart-flutter-patterns для Claude Code и Codex: готовые паттерны Dart и Flutter — null safety, состояние, навигация, сеть. Ускоряет написание и ревью кода на Flutter. CX Codex +1 6 400установок

Из того же набора39

Весь набор →
architecture-feature-first Скилл architecture-feature-first задаёт слоистую feature-first архитектуру для Flutter: где лежит UI, где данные и когда нужен доменный слой. CX Codex +1 ★ 674звёзд репо inclusive-design Скилл inclusive-design помогает проектировать интерфейсы с учётом медленного интернета, дешёвых смартфонов, нестандартных имён и низкого цифрового опыта. Не заменяет WCAG. CX Codex +1 ★ 674звёзд репо firebase-database Скилл firebase-database помогает проектировать структуру Firebase Realtime Database и работать с чтением, записями, синхронизацией и правилами доступа в приложениях Flutter. CX Codex +1 ★ 674звёзд репо dart-3-updates Скилл dart-3-updates для Claude Code и Codex учит ИИ писать switch-выражения, паттерны, records и modern Dart вместо старых if-else цепочек. Помогает при рефакторинге кода под Dart 3 и выборе между records и классами. CX Codex +1 ★ 674звёзд репо accessibility Скилл accessibility разбирает задачу по чек-листу WCAG — клавиатура, скринридер, контраст, формы — и находит конкретные нарушения доступности. Включается по словам a11y, ARIA, alt text, focus order, contrast. CX Codex +1 ★ 674звёзд репо firebase-cloud-firestore Скилл firebase-cloud-firestore учит агента настраивать Cloud Firestore во Flutter-проекте: схему данных, запросы, листенеры и правила безопасности. CX Codex +1 ★ 674звёзд репо generate-images-with-firebase-ai Скилл generate-images-with-firebase-ai помогает настроить генерацию картинок через Firebase AI Logic и Gemini в Flutter, избегая ошибок квот, сбоев App Check и пустых ответов. CX Codex +1 ★ 674звёзд репо code-review Скилл code-review проверяет изменения в Flutter/Dart-проекте по чек-листу: от логики и тестов до безопасности и стиля. Пригодится перед слиянием PR или MR. CX Codex +1 ★ 674звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой