{"id":"effective-dart","name":"effective-dart","summary":"Dartコードを書く際、スタイルのレビュー、名前のリファクタリング、ドキュメントコメントの追加、インポートの構造化、型注釈の強制などに利用してください。","body":"# Effective Dart Skill\n\nThis skill defines how to write idiomatic, high-quality Dart and Flutter code following Effective Dart guidelines.\n\n---\n\n## 1. Naming Conventions\n\n| Kind | Convention | Example |\n|---|---|---|\n| Classes, enums, typedefs, type parameters, extensions | `UpperCamelCase` | `MyWidget`, `UserState` |\n| Packages, directories, source files | `lowercase_with_underscores` | `user_profile.dart` |\n| Import prefixes | `lowercase_with_underscores` | `import '...' as my_prefix;` |\n| Variables, parameters, named parameters, functions | `lowerCamelCase` | `userName`, `fetchData()` |\n\n- Capitalize acronyms and abbreviations longer than two letters like words: `HttpRequest`, not `HTTPRequest`.\n- Avoid abbreviations unless the abbreviation is more common than the full term.\n- Prefer putting the **most descriptive noun last** in names.\n- Use terms **consistently** throughout your code.\n- Follow mnemonic conventions for type parameters: `E` (element), `K`/`V` (key/value), `T`/`S`/`U` (generic types).\n- Consider making code **read like a sentence** when designing APIs.\n- Prefer a **noun phrase** for non-boolean properties or variables.\n- Prefer a **non-imperative verb phrase** for boolean properties or variables; prefer the positive form.\n- Consider omitting the verb for named boolean parameters.\n- Avoid starting a function or method name with `get`; prefer removing `get` and using a getter when the API conceptually exposes a property.\n\n---\n\n## 2. Types and Functions\n\n- Use **class modifiers** (`final`, `sealed`, `interface`, `base`, `mixin`) to control whether a class can be extended or implemented.\n- **Type annotate variables** without initializers.\n- Type annotate **fields and top-level variables** if the type isn't obvious.\n- **Annotate return types** on function declarations.\n- **Annotate parameter types** on function declarations.\n- Write **type arguments** on generic invocations that aren't inferred.\n- Annotate with `dynamic` instead of letting inference fail.\n- Use `Future<void>` as the return type of async members that do not produce values.\n- Use **getters** for operations that conceptually access properties.\n- Use **setters** for operations that conceptually change properties.\n- Use a **function declaration** to bind a function to a name.\n- Use **inclusive start and exclusive end** parameters to accept a range.\n\n```dart\n// Prefer: explicit class modifier\nfinal class AppConfig {\n  final String apiUrl;\n  final int timeout;\n  const AppConfig({required this.apiUrl, required this.timeout});\n}\n\n// Prefer: sealed for exhaustive pattern matching\nsealed class Result<T> {}\nclass Success<T> extends Result<T> { final T value; Success(this.value); }\nclass Failure<T> extends Result<T> { final Exception error; Failure(this.error); }\n```\n\n---\n\n## 3. Style\n\n```bash\ndart format .\n```\n\n- Format code with `dart format` — don't manually format.\n- Use **curly braces** for all flow control statements.\n- Prefer `final` over `var` when variable values won't change.\n- Use `const` for compile-time constants.\n- Prefer lines **80 characters or fewer** for readability.\n\n---\n\n## 4. Imports and Files\n\n- Don't import libraries inside the `src` directory of another package.\n- Don't allow import paths to reach into or out of `lib`.\n- **Prefer relative import paths** within a package.\n- Don't use `/lib/` or `../` in import paths.\n- Consider writing a **library-level doc comment** for library files.\n\n---\n\n## 5. Structure\n\n- Keep files **focused on a single responsibility**.\n- Limit file length to maintain readability.\n- Group related functionality together.\n- Prefer making fields and top-level variables `final`.\n- Consider making constructors `const` if the class supports it.\n- **Prefer making declarations private** — only expose what's necessary.\n\n---\n\n## 6. Usage Patterns\n\n```dart\n// Adjacent string concatenation (not +)\nfinal greeting = 'Hello, '\n    'world!';\n\n// Collection literals\nfinal list = [1, 2, 3];\nfinal map = {'key': 'value'};\n\n// Initializing formals\nclass Point {\n  final double x, y;\n  Point(this.x, this.y);\n}\n\n// Empty constructor body\nclass Empty {\n  Empty();  // not Empty() {}\n}\n\n// rethrow to preserve stack trace\ntry {\n  doSomething();\n} catch (e) {\n  log(e);\n  rethrow;\n}\n```\n\n- Use `whereType<T>()` to filter a collection by type.\n- Follow a **consistent rule** for `var` and `final` on local variables.\n- Initialize fields at their **declaration** when possible.\n- Override `hashCode` if you override `==`; ensure `==` obeys mathematical equality rules.\n- **Prefer specific exception handling**: use `on SomeException catch (e)` instead of broad `catch (e)` or `.catchError` handlers.\n\n---\n\n## 7. Documentation\n\n```dart\n/// Returns the sum of [a] and [b].\n///\n/// Throws [ArgumentError] if either value is negative.\nint add(int a, int b) { ... }\n```\n\n- Format comments like sentences (capitalize, end with period).\n- Use `///` doc comments — not `/* */` block comments — for types and members.\n- Prefer writing doc comments for **public APIs**; consider them for private APIs too.\n- Start doc comments with a **single-sentence summary**, separated into its own paragraph.\n- Avoid redundancy with the surrounding context.\n- Start function/method comments with a **third-person verb** if the main purpose is a side effect.\n- Start with a **noun or non-imperative verb phrase** if returning a value is the primary purpose.\n- Start **boolean** variable/property comments with \"Whether\" followed by a noun or gerund phrase.\n- Use `[identifier]` in doc comments to refer to in-scope identifiers.\n- Use **prose** to explain parameters, return values, and exceptions (e.g., \"The [param]\", \"Returns\", \"Throws\" sections).\n- Put doc comments **before** metadata annotations.\n- Document **why** code exists or how it should be used, not just what it does.\n\n---\n\n## 8. Testing Patterns\n\n- Write **unit tests** for business logic, using `group` and descriptive `test` names:\n\n```dart\nimport 'package:test/test.dart';\n\nvoid main() {\n  group('CartService', () {\n    late CartService cart;\n\n    setUp(() => cart = CartService());\n\n    test('addItem increases item count', () {\n      cart.addItem(Product(id: '1', name: 'Widget', price: 9.99));\n      expect(cart.items, hasLength(1));\n    });\n\n    test('removeItem decreases total price', () {\n      final product = Product(id: '1', name: 'Widget', price: 9.99);\n      cart.addItem(product);\n      cart.removeItem(product.id);\n      expect(cart.totalPrice, equals(0.0));\n    });\n  });\n}\n```\n\n- Write **widget tests** using `testWidgets` and `WidgetTester`:\n\n```dart\nimport 'package:flutter_test/flutter_test.dart';\n\nvoid main() {\n  testWidgets('LoginButton shows loading indicator when tapped',\n      (WidgetTester tester) async {\n    await tester.pumpWidget(const MaterialApp(home: LoginScreen()));\n    await tester.tap(find.byType(ElevatedButton));\n    await tester.pump();\n    expect(find.byType(CircularProgressIndicator), findsOneWidget);\n  });\n}\n```\n\n---\n\n## 9. Code Review Workflow\n\nWhen reviewing Dart code for Effective Dart compliance, the agent should check:\n\n1. **Naming** — verify all identifiers follow the conventions in Section 1.\n2. **Type annotations** — confirm public API parameters, return types, and uninitialized variables are annotated.\n3. **Class modifiers** — verify `final`, `sealed`, or `interface` is used where appropriate.\n4. **Documentation** — confirm all public members have `///` doc comments with a single-sentence summary.\n5. **Style** — run `dart format --output=none --set-exit-if-changed .` to verify formatting.\n6. **Analysis** — run `dart analyze` and confirm zero issues.\n\n---\n\n## References\n\n- [Effective Dart](https://dart.dev/effective-dart)\n- [Dart Site WWW GitHub Repository](https://github.com/dart-lang/site-www)","author":"@evanca","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/evanca/flutter-ai-rules/tree/main/skills/effective-dart","license":"MIT","category":"writing","lang":"en","tokens":1835,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["dart.dev"]}}