dart-effective-style

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

dart-style-guide

Dart风格指南

Goal

目标

Applies idiomatic Dart styling, naming conventions, and formatting rules to ensure consistent, readable, and maintainable code across Dart and Flutter projects. Assumes a standard Dart SDK environment where the
dart
CLI is available.
在Dart和Flutter项目中应用符合语言习惯的Dart风格、命名规范及格式化规则,确保代码一致、可读且易于维护。本文假设你已拥有标准Dart SDK环境,且
dart
CLI可用。

Instructions

操作步骤

  1. Apply Naming Conventions Ensure all identifiers match Dart's official style guidelines. Use the Decision Logic section below to determine the correct casing for any given identifier.
  2. Order Directives Organize all imports and exports at the top of the file in the following strict order, separated by blank lines, and sorted alphabetically within each group:
    • dart:
      imports.
    • package:
      imports.
    • Relative imports.
    • export
      directives.
    dart
    import 'dart:async';
    import 'dart:collection';
    
    import 'package:bar/bar.dart';
    import 'package:foo/foo.dart';
    
    import 'util.dart';
    
    export 'src/error.dart';
  3. Format Code Always format the code using the official Dart formatter. If the formatter produces hard-to-read code, refactor the code (e.g., extract variables) to be more formatter-friendly.
    bash
    dart format .
  4. Enforce Flow Control Braces Always use curly braces for flow control statements to prevent the dangling else problem.
    dart
    // GOOD
    if (isWeekDay) {
      print('Bike to work!');
    } else {
      print('Go dancing or read a book!');
    }
    
    // ACCEPTABLE (Single line, no else)
    if (arg == null) return defaultValue;
  5. Handle Unused Callback Parameters Use wildcards (
    _
    ) for unused callback parameters to signal intent.
    dart
    futureOfVoid.then((_) {
      print('Operation complete.');
    });
    
    // Multiple unused parameters
    .onError((_, __) {
      print('Operation failed.');
    });
  1. 遵循命名规范 确保所有标识符符合Dart官方风格指南。可参考下方的决策逻辑部分,确定任意标识符的正确大小写格式。
  2. 指令排序 将所有导入与导出指令整理在文件顶部,并严格按照以下顺序排列,各组之间用空行分隔,组内按字母顺序排序:
    • dart:
      导入
    • package:
      导入
    • 相对路径导入
    • export
      指令
    dart
    import 'dart:async';
    import 'dart:collection';
    
    import 'package:bar/bar.dart';
    import 'package:foo/foo.dart';
    
    import 'util.dart';
    
    export 'src/error.dart';
  3. 代码格式化 始终使用官方Dart格式化工具格式化代码。如果格式化后的代码可读性变差,请重构代码(例如提取变量),使其更适配格式化工具。
    bash
    dart format .
  4. 强制使用流控制大括号 流控制语句必须使用大括号,以避免悬空else问题。
    dart
    // 规范写法
    if (isWeekDay) {
      print('Bike to work!');
    } else {
      print('Go dancing or read a book!');
    }
    
    // 可接受写法(单行且无else分支)
    if (arg == null) return defaultValue;
  5. 处理未使用的回调参数 对于未使用的回调参数,使用通配符
    _
    来明确表达意图。
    dart
    futureOfVoid.then((_) {
      print('Operation complete.');
    });
    
    // 多个未使用参数
    .onError((_, __) {
      print('Operation failed.');
    });

Decision Logic

决策逻辑

When creating or renaming an identifier, follow this flowchart logic:
  • Is it a Class, Enum, Typedef, Extension, or Type Parameter?
    • Yes: Use
      UpperCamelCase
      .
      dart
      class SliderMenu {}
      typedef Predicate<T> = bool Function(T value);
      extension SmartIterable<T> on Iterable<T> {}
  • Is it a Package, Directory, Source File, or Import Prefix?
    • Yes: Use
      lowercase_with_underscores
      .
      dart
      import 'dart:math' as math;
      import 'package:js/js.dart' as js;
      // File: slider_menu.dart
  • Is it a Constant Variable or Enum Value?
    • Yes: Use
      lowerCamelCase
      (Do NOT use
      SCREAMING_CAPS
      unless matching legacy code).
      dart
      const pi = 3.14;
      const defaultTimeout = 1000;
  • Is it a Variable, Parameter, Named Parameter, Class Member, or Top-Level Definition?
    • Yes: Use
      lowerCamelCase
      .
      dart
      var count = 3;
      HttpRequest httpRequest;
  • Does the name contain an Acronym or Abbreviation?
    • Is it longer than two letters? Capitalize it like a normal word (e.g.,
      Http
      ,
      Uri
      ).
    • Is it exactly two letters? Keep both capitalized (e.g.,
      ID
      ,
      TV
      ) unless it is the start of a
      lowerCamelCase
      identifier, in which case both are lowercase (e.g.,
      idToken
      ,
      tvSet
      ).
  • Is the member or top-level declaration meant to be private to its library?
    • Yes: Prefix it with a leading underscore
      _
      .
    • No: Do NOT use a leading underscore. (Never use leading underscores for local variables or parameters).
创建或重命名标识符时,请遵循以下流程逻辑:
  • 是否为类、枚举、类型定义、扩展或类型参数?
    • 是: 使用
      UpperCamelCase
      格式。
      dart
      class SliderMenu {}
      typedef Predicate<T> = bool Function(T value);
      extension SmartIterable<T> on Iterable<T> {}
  • 是否为包、目录、源文件或导入前缀?
    • 是: 使用
      lowercase_with_underscores
      格式。
      dart
      import 'dart:math' as math;
      import 'package:js/js.dart' as js;
      // 文件: slider_menu.dart
  • 是否为常量变量或枚举值?
    • 是: 使用
      lowerCamelCase
      格式(除非适配遗留代码,否则请勿使用
      SCREAMING_CAPS
      格式)。
      dart
      const pi = 3.14;
      const defaultTimeout = 1000;
  • 是否为变量、参数、命名参数、类成员或顶层定义?
    • 是: 使用
      lowerCamelCase
      格式。
      dart
      var count = 3;
      HttpRequest httpRequest;
  • 名称中是否包含首字母缩写或缩写词?
    • 长度超过两个字母? 像普通单词一样大写首字母(例如
      Http
      Uri
      )。
    • 恰好两个字母? 两个字母都大写(例如
      ID
      TV
      ),除非它是
      lowerCamelCase
      标识符的开头,此时两个字母都小写(例如
      idToken
      tvSet
      )。
  • 成员或顶层声明是否仅对其所在库可见(私有)?
    • 是: 在名称前添加下划线
      _
      前缀。
    • 否: 请勿添加下划线前缀。(局部变量或参数绝不能使用下划线前缀)。

Constraints

约束条件

  • Mandatory Formatting: DO run
    dart format
    as a mandatory step before committing or finalizing any code changes.
  • Import Preferences: PREFER relative imports for files located inside the
    lib
    directory of the same package.
  • No Prefix Letters: DON'T use prefix letters (like Hungarian notation). Use
    defaultTimeout
    , not
    kDefaultTimeout
    .
  • No Explicit Library Names: DON'T explicitly name libraries (e.g., avoid
    library my_library;
    ). Use
    library;
    if a directive is needed for annotations.
  • Line Length: PREFER lines 80 characters or fewer. STOP AND ASK THE USER: if a specific string or configuration requires exceeding the 80-character limit and cannot be reasonably refactored.
  • Related Skills:
    dart-static-analysis
    ,
    dart-api-design
    .
  • 强制格式化: 在提交或完成任何代码变更前,必须执行
    dart format
    命令。
  • 导入偏好: 对于同一包内
    lib
    目录下的文件,优先使用相对路径导入。
  • 禁止前缀字母: 请勿使用前缀字母(如匈牙利命名法)。应使用
    defaultTimeout
    而非
    kDefaultTimeout
  • 禁止显式库名: 请勿显式命名库(例如避免使用
    library my_library;
    )。如果注解需要库指令,请使用
    library;
  • 行长度: 每行长度建议不超过80个字符。若特定字符串或配置需要超过80字符限制且无法合理重构,请暂停并询问用户。
  • 相关技能:
    dart-static-analysis
    ,
    dart-api-design
    .