dart-rules

Dart/Flutter 编码规范,涵盖风格、设计模式、安全性与测试。用于在检测到 Dart/Flutter 相关文件或技术时应用规范。触发条件:.dart 文件、pubspec.yaml、Flutter、Riverpod、Bloc、widget、StatelessWidget、StatefulWidget。

仓库最近推送
GitHub Stars
180
Forks
21
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "dart-rules":https://skillpi.com/zh/skills/deepskill-b45f9ca5a5ab8b448f103a4852f2a5f36ba91ee9a2930f43515974fea0fa101a。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

Dart/Flutter 编码规范,涵盖风格、设计模式、安全性与测试。用于在检测到 Dart/Flutter 相关文件或技术时应用规范。触发条件:.dart 文件、pubspec.yaml、Flutter、Riverpod、Bloc、widget、StatelessWidget、StatefulWidget。

0 下载

介绍来源: third_party · softspark · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: dart-rules
description: "Dart/Flutter coding rules: style, patterns, security, testing. Triggers: .dart, pubspec.yaml, Flutter, Riverpod, Bloc, widget, StatelessWidget, StatefulWidget."
effort: medium
user-invocable: false
allowed-tools: Read

Dart/Flutter Rules

These rules come from app/rules/dart/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in Dart/Flutter. Apply them when writing or reviewing Dart/Flutter code.

Dart Coding Style

Naming

  • PascalCase: classes, enums, typedefs, extensions, mixins.
  • camelCase: variables, functions, methods, parameters, named constants.
  • snake_case: libraries, packages, directories, source files.
  • UPPER_SNAKE: not used in Dart. Use camelCase for constants.
  • Prefix private members with _: _internalState, _helper().

Null Safety

  • Enable sound null safety (default since Dart 2.12).
  • Use ? types only when null is semantically meaningful.
  • Use ! operator sparingly. Prefer null checks or ?? fallback.
  • Use late keyword only when initialization is guaranteed before access.
  • Use required keyword for mandatory named parameters.

Classes

  • Use const constructors for immutable classes.
  • Use factory constructors for caching, subtype selection, or validation.
  • Use named constructors for clarity: Point.fromJson(json).
  • Use final fields for immutable properties.
  • Use @immutable annotation on classes that should be immutable.

Functions

  • Use named parameters for functions with >2 parameters.
  • Use required for mandatory named parameters.
  • Use default values for optional parameters.
  • Use fat arrow (=>) for single-expression functions.
  • Always specify return types for public functions.

Collections

  • Use collection literals: [], {}, <String, int>{}.
  • Use if and for inside collection literals for conditional/iterative building.
  • Use spread operator: [...list1, ...list2].
  • Use whereType<T>() for type-safe filtering.
  • Prefer const collections when values are known at compile time.

Async

  • Use async/await for all asynchronous operations.
  • Return Future<T> from async functions. Never return void.
  • Use Stream<T> for continuous data (events, real-time updates).
  • Use Future.wait() for concurrent independent operations.
  • Use Completer<T> only when wrapping callback-based APIs.

Imports

  • Order: dart: SDK, package: external, relative project imports.
  • Use show/hide to limit import scope when names conflict.
  • Use as prefix for namespace conflicts: import 'package:foo/foo.dart' as foo.
  • Prefer relative imports within the same package.

Formatting

  • Use dart format (line length 80) for consistent formatting.
  • Use dart analyze for static analysis with default lint rules.
  • Use analysis_options.yaml with recommended lints: flutter_lints or lints.
  • Use trailing commas in multi-line argument lists for cleaner diffs.

Dart Frameworks

Flutter

  • Use StatelessWidget by default. Use StatefulWidget only for local state.
  • Use const constructors and const widgets for build optimization.
  • Use Key parameters for widgets in lists for correct diffing.
  • Extract large build() methods into smaller widget classes (not methods).
  • Use Theme.of(context) and TextTheme for consistent styling.

Navigation

  • Use GoRouter for declarative, type-safe routing.
  • Define routes as constants: static const String home = '/home'.
  • Use ShellRoute for persistent navigation bars across routes.
  • Use context.go() for navigation, context.push() for stacking.
  • Pass arguments via path parameters or extra for complex objects.

Networking

  • Use dio for HTTP with interceptors, retry, and cancellation.
  • Use retrofit (code gen) for type-safe REST client definitions.
  • Use interceptors for auth token injection and refresh logic.
  • Set timeouts on every request: connectTimeout, receiveTimeout.
  • Use CancelToken for cancelling in-flight requests on navigation.

JSON Serialization

  • Use json_serializable (+ build_runner) for generated fromJson/toJson. Default fieldRename: FieldRename.none uses Dart property names as-is — combined with Effective Dart lowerCamelCase, this produces camelCase JSON keys with zero configuration.
  • Flutter docs recommend: "best if both server and client follow the same naming strategy" (Flutter — JSON and serialization). When they do, no mapping is needed.
  • When server uses a different convention, prefer @JsonSerializable(fieldRename: FieldRename.snake) at the class level (or globally in build.yaml) over sprinkling @JsonKey(name:) on every field. Community recommendation from the json_serializable docs and pub.dev guides.
  • Use individual @JsonKey(name: '...') only for exceptional cases: external API with mixed conventions, reserved Dart keyword collision (class, is, new), or legacy field rename during deprecation window. Document the reason in a comment.
  • For enum / status / permission values on the wire: UPPER_SNAKE_CASE is the cross-language community consensus (see common/coding-style.md — JSON Wire Format Conventions). Dart enum case names themselves stay lowerCamelCase per Effective Dart; map them to uppercase strings in fromJson/toJson (value.toUpperCase() + switch).
  • Write unit tests asserting both directions (fromJson + toJson) with explicit expected keys. Catches contract drift at CI time.

Local Storage

  • Use shared_preferences for simple key-value persistence.
  • Use drift (formerly Moor) for type-safe SQLite with reactive queries.
  • Use hive for fast, lightweight NoSQL local storage.
  • Use flutter_secure_storage for sensitive data (tokens, passwords).
  • Never store secrets in shared_preferences (not encrypted).

Dependency Injection

  • Use get_it for service locator pattern. Register at app startup.
  • Use injectable (code gen) for automatic registration from annotations.
  • Use Riverpod providers as DI containers for testable architecture.
  • Register singletons for services, factories for per-use instances.

Platform Channels

  • Use MethodChannel for invoking native (iOS/Android) code.
  • Use EventChannel for streaming data from native to Dart.
  • Use Pigeon (code gen) for type-safe platform channel definitions.
  • Handle MissingPluginException gracefully on unsupported platforms.

Testing Frameworks

  • Use flutter_test for widget tests with WidgetTester.
  • Use integration_test package for full app integration tests.
  • Use patrol for native-aware integration testing (permissions, notifications).
  • Use golden_toolkit for advanced visual regression testing.

Build and CI

  • Use flutter build with --release and --dart-define for env configuration.
  • Use flavors (--flavor) for dev/staging/prod build variants.
  • Use flutter analyze in CI for static analysis enforcement.
  • Use flutter test --coverage with lcov for coverage reporting.

Dart Patterns

Error Handling

  • Use typed exceptions for domain errors: class UserNotFoundException implements Exception.
  • Use try-catch with specific exception types. Avoid bare catch (e).
  • Use rethrow to preserve stack trace when re-raising exceptions.
  • Use Result<T, E> pattern (e.g., dartz Either) for expected failures.
  • Use Future.catchError() only when async/await is not applicable.

State Management (Flutter)

  • Use Riverpod for compile-safe, testable state management.
  • Use BLoC pattern for event-driven state with clear input/output.
  • Use ChangeNotifier / ValueNotifier for simple local state.
  • Use StateNotifier (Riverpod) for immutable state transitions.
  • Keep state classes immutable. Use copyWith() for updates.

Riverpod

  • Use @riverpod annotation (code gen) for provider definitions.
  • Use ref.watch() for reactive dependencies. Use ref.read() for one-time access.
  • Use AsyncNotifier for async state management.
  • Use autoDispose for providers that should clean up when unused.
  • Use family modifier for parameterized providers.

BLoC Pattern

  • Separate events (input), states (output), and logic (bloc).
  • Use sealed class for events and states (exhaustive switch).
  • Use Emitter<State> for emitting state transitions.
  • Use transformEvents() for debouncing search inputs.
  • Use BlocObserver for global logging and error tracking.

Repository Pattern

  • Abstract data sources behind repository interfaces.
  • Repositories return domain models, not DTOs or raw data.
  • Use Future<T> for single values, Stream<T> for real-time updates.
  • Cache data in repository layer when appropriate.
  • Inject repositories via constructor. Use Riverpod/GetIt for DI.

Freezed (Code Generation)

  • Use @freezed for immutable data classes with copyWith, equality, toString.
  • Use @freezed sealed unions for state modeling: factory State.loading().
  • Use when() / map() for exhaustive pattern matching on freezed unions.
  • Run dart run build_runner build after modifying freezed classes.

Async Patterns

  • Use Stream.asyncMap() for transforming streams with async operations.
  • Use StreamController<T> for custom streams. Close in dispose().
  • Use Completer<T> to bridge callback APIs to Future-based APIs.
  • Use Timer.periodic() for polling. Cancel in dispose().
  • Use compute() (Flutter) for CPU-intensive work on isolates.

Anti-Patterns

  • Using dynamic type: defeats type safety. Use Object? or generics.
  • Not disposing controllers/subscriptions: causes memory leaks.
  • Putting business logic in widgets: extract to services/blocs.
  • Using setState() for global state: use proper state management.
  • Deep widget nesting: extract sub-widgets as separate classes.

Dart Security

Input Validation

  • Validate all user input in form fields with TextFormField validators.
  • Use RegExp for pattern validation (email, phone, URL).
  • Sanitize HTML content before rendering. Never use Html widget with raw user input.
  • Validate deep link parameters before navigation or data loading.
  • Limit text input length with maxLength on TextFormField.

Network Security

  • Use HTTPS exclusively. Configure SecurityContext for certificate pinning.
  • Use dio interceptors for consistent auth header injection.
  • Validate SSL certificates in production. Do not disable certificate checks.
  • Set connection and read timeouts on all HTTP requests.
  • Use CancelToken to abort requests when the user navigates away.

Data Storage

  • Use flutter_secure_storage for tokens, passwords, and API keys.
  • Never store sensitive data in shared_preferences (stored in plaintext).
  • Encrypt local databases (drift with sqlcipher, or hive with encryption).
  • Clear secure storage on user logout.
  • Use kIsWeb checks to handle web platform storage limitations.

Authentication

  • Use OAuth 2.0 / OIDC with PKCE flow for mobile authentication.
  • Store refresh tokens in secure storage. Store access tokens in memory.
  • Use flutter_appauth for standards-compliant OAuth flows.
  • Implement biometric authentication with local_auth package.
  • Never store credentials in Dart source code or asset files.

Platform Channel Security

  • Validate all data received from native code via platform channels.
  • Do not pass sensitive data through MethodChannel logging-enabled calls.
  • Use Pigeon for type-safe channel communication (prevents mismatched types).
  • Handle PlatformException gracefully for missing native implementations.

Obfuscation and Hardening

  • Use --obfuscate --split-debug-info=<dir> for release builds.
  • Use --dart-define for environment-specific configuration (not secrets).
  • Do not embed API keys in the Dart source. Use server-side proxying.
  • Use ProGuard rules (Android) and symbol stripping (iOS) for native code.

WebView Security

  • Use webview_flutter with JavaScript disabled unless explicitly needed.
  • Restrict navigation to allowlisted domains with NavigationDelegate.
  • Sanitize any data passed from WebView to Dart via JavaScript channels.
  • Do not load untrusted URLs in WebViews.

Dependency Security

  • Run dart pub outdated regularly. Update dependencies promptly.
  • Audit pubspec.lock for unexpected transitive dependencies.
  • Use dart pub audit (when available) for vulnerability scanning.
  • Prefer well-maintained packages with high pub.dev scores.
  • Pin exact versions in pubspec.yaml for production apps.

Dart Testing

Framework

  • Use package:test for pure Dart unit tests.
  • Use package:flutter_test for Flutter widget and integration tests.
  • Use package:mockito with @GenerateMocks for mock generation.
  • Use package:mocktail as a simpler alternative (no code generation).

File Naming

  • Test files: foo_test.dart in test/ mirroring lib/ structure.
  • Widget tests: test/widgets/ for Flutter widget tests.
  • Integration tests: integration_test/ directory (Flutter convention).
  • Golden tests: test/goldens/ for visual regression snapshots.

Structure

  • Use group() for organizing related tests.
  • Use setUp() / tearDown() for per-test setup and cleanup.
  • Use setUpAll() / tearDownAll() for expensive one-time setup.
  • Name tests descriptively: test('returns null when user is not found', ...).

Assertions

  • Use expect(actual, matcher) with built-in matchers.
  • Use equals(), isNull, isNotNull, isA<T>() for type/value checks.
  • Use throwsA(isA<FormatException>()) for exception testing.
  • Use completion(expected) for Future assertions.
  • Use emitsInOrder([...]) for Stream emission testing.

Mocking (Mockito)

  • Annotate: @GenerateMocks([UserRepository]). Run build_runner.
  • Stub: when(mock.getUser(any)).thenAnswer((_) async => user).
  • Verify: verify(mock.saveUser(captureAny)).called(1).
  • Use verifyNever() to assert a method was not called.
  • Use throwOnMissingStub() to catch unstubbed method calls.

Widget Testing (Flutter)

  • Use testWidgets('description', (tester) async { ... }).
  • Use tester.pumpWidget(MaterialApp(home: MyWidget())) to render.
  • Use tester.pump() to trigger rebuilds after state changes.
  • Use tester.pumpAndSettle() to wait for animations to complete.
  • Use find.byType(), find.text(), find.byKey() for widget lookups.
  • Use tester.tap(), tester.enterText() for interaction simulation.

Golden Tests

  • Use matchesGoldenFile('goldens/my_widget.png') for visual comparison.
  • Run flutter test --update-goldens to regenerate baseline images.
  • Use golden tests for complex UI components, not simple widgets.
  • Keep golden tests platform-specific (render output varies by OS).

Best Practices

  • Test public API behavior, not implementation details.
  • Use fake classes (implementing interfaces) for simple test doubles.
  • Use addTearDown() to register cleanup in the test body.
  • Run flutter test --coverage and check coverage/lcov.info.
  • Use blocTest() from bloc_test package for BLoC testing.

版本历史

  1. v6.2.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    原版更新说明

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    原版更新说明

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    原版更新说明

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值75/100

亮点

  • 提供全面的 Dart/Flutter 编码规范,涵盖风格、框架、模式、安全性和测试
  • 适用于开发者日常编码实践,具有明确的实用价值
触发精准90/100

亮点

  • 触发条件明确且完整,覆盖 .dart 文件、Flutter 相关关键词等合理场景
结构规范70/100

待提升项

  • 缺少 When to Use 和端到端示例 原报告严重程度:轻微

    文档结构清晰但缺少 When to Use 章节和具体使用示例

    改进建议:建议补充 When to Use 说明和端到端使用示例以增强可读性

亮点

  • 文档结构清晰,分章节组织,frontmatter 完整
执行可靠90/100

亮点

  • 纯文档型规则集,内容来源可靠,无执行风险
证据可验 (前四项均值)81/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • docs.flutter.dev

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。