Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 61 ยท Real-World Dart

Effective Dart: Style, Lints and Formatting

Write idiomatic Dart: naming conventions, analysis_options.yaml, lint rules, dart format, dart fix and documentation comments, with runnable stand-ins.

Code is read far more often than it is written. A project where every file follows the same conventions is easier to scan, review and change. The Dart community settled on a shared set of habits, collected in the guide called Effective Dart, and the tools that come with the SDK enforce most of them for you.

This lesson covers four things: naming rules, the analyzer and its lint rules (configured in analysis_options.yaml), the formatter (dart format), and documentation comments. The Dart code and commands are read-only here; the TypeScript stand-ins implement tiny versions of a naming checker and a doc-comment extractor so you can see how such tools work.

Naming conventions

Dart uses capitalization to tell you what a name is:

Kind Style Examples
Classes, enums, typedefs, extensions, type parameters UpperCamelCase ShoppingCart, HttpClient, T
Variables, fields, parameters, functions, methods lowerCamelCase itemCount, fetchUser()
Constants (including const and enum values) lowerCamelCase defaultTimeout, Color.red
Libraries, packages, directories, source files lowercase_with_underscores shopping_cart.dart, my_package
Import prefixes lowercase_with_underscores import '...' as math_utils;
Private members leading underscore _cache, _parse()

Two points surprise people from other languages. First, constants are not SCREAMING_CASE: write const maxRetries = 3;, not MAX_RETRIES. Second, acronyms longer than two letters are written like ordinary words: HttpRequest, Uri, JsonParser, not HTTPRequest. Two-letter acronyms keep their capitals, as in IOSink.

Other naming habits:

  • Name booleans as questions or states: isEmpty, hasChildren, canClose.
  • Prefer nouns for properties and verbs for methods: cart.total, cart.checkout().
  • Do not prefix a name with its type (strName) or add I to interfaces (IUser). Every class is an interface already.
  • Use _ as the name of a parameter or variable you intentionally ignore, and start private names with _ only when the library boundary matters (see getters, setters and library privacy).
TypeScript A tiny naming checker (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Style habits worth knowing

A few more rules from Effective Dart that shape everyday code:

DART
// Prefer collection literals.
final names = <String>[];            // not List<String>()
final ages = <String, int>{};

// Use isEmpty / isNotEmpty, not length comparisons.
if (names.isEmpty) return;

// Prefer expression bodies for one-liners.
int double(int x) => x * 2;

// Use string interpolation instead of +.
final greeting = 'Hello, $name! You have ${items.length} items.';

// Prefer final for variables that never change.
final total = prices.fold(0, (a, b) => a + b);

// Use ?? and ?. for null handling.
final label = user?.nickname ?? 'guest';

// Do not use a block just to return a value you can write as an expression.
bool isAdult(int age) => age >= 18;

Other advice: annotate the types of public APIs (function parameters, return types and fields), omit types on local variables when the right side makes them obvious, avoid dynamic unless you truly mean "anything", avoid ! unless you can prove the value is not null, and keep lines short enough to read. The ideas behind these rules appear throughout the earlier lessons on null safety and variables.

The analyzer

The analyzer reads your code without running it and reports problems at three levels: errors (the code will not compile), warnings (probably a bug, such as an unused variable) and lints (style and best-practice suggestions). Run it with:

TEXT
dart analyze

Editors run the same analyzer continuously, which is why VS Code and IntelliJ underline problems as you type. In continuous integration, dart analyze --fatal-infos makes even lints fail the build.

analysis_options.yaml

The analyzer reads analysis_options.yaml at the root of your package. A typical file looks like this:

YAML
include: package:lints/recommended.yaml

analyzer:
  language:
    strict-casts: true
    strict-inference: true
    strict-raw-types: true
  exclude:
    - "**/*.g.dart"
  errors:
    unused_import: error

linter:
  rules:
    - prefer_const_constructors
    - prefer_final_locals
    - avoid_print
    - always_declare_return_types

Piece by piece:

  • include loads a ready-made rule set. Dart projects usually start from package:lints/recommended.yaml (or core.yaml for fewer rules); Flutter projects use package:flutter_lints/flutter.yaml. Add the package with dart pub add --dev lints.
  • The three strict-* options make the type system stricter: no silent casts from dynamic, no types that fall back to dynamic by inference, and no raw generic types such as a bare List.
  • exclude skips files, typically generated code like the .g.dart files from json_serializable.
  • errors changes the severity of a rule: make unused_import an error, or silence a rule with ignore.
  • linter: rules turns individual lint rules on on top of the included set.

You can suppress a single warning when you have a good reason, with a comment on the line above: // ignore: avoid_print. Use it sparingly and, if the reason is not obvious, say why.

flowchart LR
    S["Your source code"] --> A["dart analyze<br/>(analyzer)"]
    O["analysis_options.yaml<br/>include + rules"] --> A
    A --> R["Errors, warnings, lints"]
    R --> F["dart fix --apply<br/>fixes many automatically"]
    R --> M["You fix the rest"]

The analyzer combines your code with your chosen rules; many findings have automatic fixes.

dart fix

Many lints come with an automatic repair. dart fix --dry-run shows what would change and dart fix --apply applies it. The command is also the usual way to adopt new language features: after upgrading the SDK it can rewrite old patterns into current ones.

TypeScript A tiny lint rule (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The formatter

Nobody should argue about spaces and line breaks. dart format rewrites code into one standard layout:

TEXT
dart format .                      # format everything in place
dart format --output=none --set-exit-if-changed .   # check only (for CI)

Rules you will notice: two-space indentation, a default line width of 80 characters, and trailing commas that control layout. If you end an argument list or collection with a comma, the formatter puts one item per line; without it, it tries to fit everything on one line.

DART
// Without a trailing comma the formatter may squeeze this together.
final widget = Container(width: 100, height: 50, color: red);

// With a trailing comma, one argument per line, always.
final widget2 = Container(
  width: 100,
  height: 50,
  color: red,
);

Recent SDKs (3.7 and newer) use an updated style that handles trailing commas automatically, and you can set the line width in analysis_options.yaml under formatter: page_width:. Which version of the style applies depends on the sdk constraint in pubspec.yaml. Format on save in your editor and check formatting in CI, and the topic disappears from code reviews.

Documentation comments

Comments starting with /// document the declaration that follows. The tool dart doc turns them into a website, and editors show them in hover tips and code completion.

DART
/// A shopping cart that holds [Item]s and computes their total price.
///
/// Prices are stored in cents to avoid rounding errors:
///
/// ```dart
/// final cart = Cart()..add(const Item('pen', 150));
/// print(cart.totalCents); // 150
/// ```
class Cart {
  /// Adds [item] to the cart.
  ///
  /// Throws an [ArgumentError] if the quantity is not positive.
  void add(Item item) { /* ... */ }

  /// The sum of price times quantity, in cents.
  int get totalCents => 0;
}

Guidelines for good doc comments:

  1. Start with a one-sentence summary in its own paragraph; tools show it in lists.
  2. Use square brackets to link to code: [Item], [add], [Cart.totalCents].
  3. Document every public member of a library, and say what throws.
  4. Describe behavior and promises, not implementation. Do not repeat what the name already says ("Gets the name" on name).
  5. Put the description above annotations; use ordinary // comments for notes to maintainers inside method bodies.

The lint public_member_api_docs can enforce documentation for libraries you publish on pub.dev.

TypeScript Extracting doc comments (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A practical routine

  1. Create new projects with dart create, which already adds lints and an analysis_options.yaml.
  2. Turn on the strict analyzer options early; they are painful to add to a large old codebase.
  3. Format on save, and run dart format --set-exit-if-changed, dart analyze and dart test in CI.
  4. Treat a lint as a conversation: fix it, or switch the rule off for the whole project if the team disagrees. Avoid scattering ignore comments.
  5. After upgrading the SDK, run dart fix --apply.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is the conventional Dart style for a constant?

    Dart uses lowerCamelCase for constants, not SCREAMING_CASE.
  2. 2. Which file name follows Dart conventions?

    Source files use lowercase_with_underscores.
  3. 3. What does include: package:lints/recommended.yaml do in analysis_options.yaml?

    include pulls in another options file, so you start from a curated rule set and add or override rules.
  4. 4. How do you control whether the formatter puts one argument per line?

    In the classic style, a trailing comma tells the formatter to split the list across lines.
  5. 5. Which comment form is used for documentation that dart doc turns into web pages?

    Triple-slash comments document the declaration that follows, and [name] links to other code.

Summary

  • Types are UpperCamelCase; variables, members and constants are lowerCamelCase; files and packages use lowercase_with_underscores.
  • dart analyze reports errors, warnings and lints; configure rules in analysis_options.yaml with include, analyzer and linter.
  • Turn on strict-casts, strict-inference and strict-raw-types for safer code; use dart fix --apply for automatic repairs.
  • dart format gives one layout for everyone; run it on save and in CI.
  • Document public APIs with ///, start with a one-sentence summary and link code with [name].

Next: performance and memory.