Coding conventions

suggest change

Dart has one official style guide, Effective Dart, and the SDK ships the tools that enforce it:

Because almost every Dart project uses the same tools, Dart code looks the same in every project. This article goes through the conventions that matter most and shows what the tools say when you break them. All output is from Dart 3.13 with package:lints 6.0.

Letting the tools find violations

dart create puts this analysis_options.yaml in every new project:

include: package:lints/recommended.yaml

To see what that catches, here is a file that ignores most naming conventions, saved as lib/src/BadStyle.dart:

import 'dart:math';
import 'package:path/path.dart' as Path;
import 'dart:async';

const MAX_RETRIES = 3;

class http_client {
  String? BaseUrl;
  http_client(String baseUrl) {
    this.BaseUrl = baseUrl;
  }

  String describe() {
    return 'Client for ' + BaseUrl! + ' with ' + MAX_RETRIES.toString() + ' retries';
  }
}

int Square(int x) => x * x;

void main() {
  var names = new List<String>.empty(growable: true);
  names.add('a');
  if (names.length == 0) print('empty');
  print(Path.join('a', 'b'));
  print(sqrt(Square(4)));
  Future.value(1);
}
$ dart analyze
Analyzing conv_demo...

   info - lib\src\BadStyle.dart:1:1 - The file name 'BadStyle.dart' isn't a lower_case_with_underscores identifier. Try changing the name to follow the lower_case_with_underscores style. - file_names
   info - lib\src\BadStyle.dart:2:36 - The prefix 'Path' isn't a lower_case_with_underscores identifier. Try changing the prefix to follow the lower_case_with_underscores style. - library_prefixes
   info - lib\src\BadStyle.dart:5:7 - The constant name 'MAX_RETRIES' isn't a lowerCamelCase identifier. Try changing the name to follow the lowerCamelCase style. - constant_identifier_names
   info - lib\src\BadStyle.dart:7:7 - The type name 'http_client' isn't an UpperCamelCase identifier. Try changing the name to follow the UpperCamelCase style. - camel_case_types
   info - lib\src\BadStyle.dart:8:11 - The variable name 'BaseUrl' isn't a lowerCamelCase identifier. Try changing the name to follow the lowerCamelCase style. - non_constant_identifier_names
   info - lib\src\BadStyle.dart:10:5 - Unnecessary 'this.' qualifier. Try removing 'this.'. - unnecessary_this
   info - lib\src\BadStyle.dart:14:12 - Use interpolation to compose strings and values. Try using string interpolation to build the composite string. - prefer_interpolation_to_compose_strings
   info - lib\src\BadStyle.dart:14:39 - Use interpolation to compose strings and values. Try using string interpolation to build the composite string. - prefer_interpolation_to_compose_strings
   info - lib\src\BadStyle.dart:18:5 - The variable name 'Square' isn't a lowerCamelCase identifier. Try changing the name to follow the lowerCamelCase style. - non_constant_identifier_names
   info - lib\src\BadStyle.dart:21:15 - Unnecessary 'new' keyword. Try removing the 'new' keyword. - unnecessary_new
   info - lib\src\BadStyle.dart:23:7 - Use 'isEmpty' instead of 'length' to test whether the collection is empty. Try rewriting the expression to use 'isEmpty'. - prefer_is_empty

11 issues found.

Every message ends with the name of the lint rule. Search for that name on dart.dev/lints to read why the rule exists.

dart fix can't rename things for you, but it handles the mechanical rewrites:

$ dart fix --dry-run
Computing fixes in conv_demo (dry run)...

4 proposed fixes in 1 file.

lib\src\BadStyle.dart
  prefer_interpolation_to_compose_strings - 1 fix
  prefer_is_empty - 1 fix
  unnecessary_new - 1 fix
  unnecessary_this - 1 fix

To fix an individual diagnostic, run one of:
  dart fix --apply --code=prefer_interpolation_to_compose_strings
  dart fix --apply --code=prefer_is_empty
  dart fix --apply --code=unnecessary_new
  dart fix --apply --code=unnecessary_this

To fix all diagnostics, run:
  dart fix --apply

dart fix is also how you update code when an SDK or package deprecates an API, so run it after upgrading.

Naming

Dart uses just three naming styles:

Style Used for Examples
UpperCamelCase classes, enums, mixins, extensions, typedefs, type parameters HttpClient, LogLevel, JsonMap, T
lowerCamelCase variables, parameters, functions, methods, fields, constants, enum values, named parameters baseUrl, maxRetries, toJson(), LogLevel.warning
lowercase_with_underscores packages, directories, file names, import prefixes http_client.dart, lib/src/, as p

Here is the earlier file written the conventional way, as lib/src/http_client.dart:

import 'package:path/path.dart' as p;

const maxRetries = 3;
const defaultTimeout = Duration(seconds: 30);

enum LogLevel { debug, info, warning, error }

typedef JsonMap = Map<String, Object?>;

extension StringCasing on String {
  String capitalize() => isEmpty ? this : this[0].toUpperCase() + substring(1);
}

class HttpClient {
  final String baseUrl;
  int _requestCount = 0;

  HttpClient(this.baseUrl);

  bool get isIdle => _requestCount == 0;

  String urlFor(String path) => p.url.join(baseUrl, path);

  void send(String path) {
    _requestCount++;
    print('GET ${urlFor(path)} (retries: $maxRetries)');
  }
}

void main() {
  final client = HttpClient('https://api.example.com');
  print(client.isIdle);
  client.send('users');
  print(client.isIdle);
  print('warning'.capitalize());
  print(LogLevel.warning.name);
}
true
GET https://api.example.com/users (retries: 3)
false
Warning
warning

Some details that trip up people coming from other languages:

Use _ for values you don't need

Since Dart 3.7, a parameter or pattern variable named _ is a wildcard: it doesn't create a variable, so you can use it several times:

void main() {
  final scores = {'alice': 90, 'bob': 72};
  scores.forEach((_, score) => print(score));

  final (name, _) = ('Alice', 30);
  print(name);

  // Dart 3.7+: `_` doesn't bind, so it can be used more than once
  int pick(int _, int _, int third) => third;
  print(pick(1, 2, 3));
}
90
72
Alice
3

Write (_, _) rather than the old (_, __) workaround.

Choosing names

Effective Dart also has advice about which words to use:

Files, directories and imports

Package layout is a convention too. Code under lib/ is the public library; implementation files go in lib/src/, which other packages shouldn't import directly. Executables go in bin/, tests in test/ with names ending in _test.dart. See Pub for more about packages.

Imports are grouped and sorted in this order, with a blank line between groups:

  1. dart: imports
  2. package: imports
  3. relative imports
  4. export directives, in a separate section after all imports

Within each group, sort alphabetically. Add the directives_ordering lint to have this checked:

import 'models.dart';
import 'package:path/path.dart' as p;
import 'dart:io';
import 'dart:convert';
   info - lib\src\service.dart:2:1 - Place 'package:' imports before relative imports. Try sorting the directives. - directives_ordering
   info - lib\src\service.dart:3:1 - Place 'dart:' imports before other imports. Try sorting the directives. - directives_ordering
   info - lib\src\service.dart:4:1 - Place 'dart:' imports before other imports. Try sorting the directives. - directives_ordering

dart fix --apply --code=directives_ordering sorts them for you:

import 'dart:convert';
import 'dart:io';

import 'package:path/path.dart' as p;

import 'models.dart';

Inside lib/, use relative imports for other files of the same package (or package: imports, but don't mix both for the same file). Never write import '../lib/src/foo.dart' from bin/ or test/; use package:my_app/src/foo.dart there.

Formatting with dart format

Don't format by hand. dart format . rewrites every file in place, and most editors run it on save. Take this badly laid-out code:

class Point{final int x,y;const Point(this.x,this.y);
int distanceTo(Point other){return (x-other.x).abs()+(y-other.y).abs();}}
void main(){
final p=Point(1,2);if(p.x>0)print('positive');
final user = createUser(name: 'Alice', email: 'alice@example.com', age: 30, admin: false);
final short = createUser(name: 'Bob', email: 'b', age: 1, admin: true,);
print([user,short,p.distanceTo(const Point(4,6))]);
}
String createUser({required String name, required String email, required int age, required bool admin}) => '$name <$email>';

After dart format a.dart:

class Point {
  final int x, y;
  const Point(this.x, this.y);
  int distanceTo(Point other) {
    return (x - other.x).abs() + (y - other.y).abs();
  }
}

void main() {
  final p = Point(1, 2);
  if (p.x > 0) print('positive');
  final user = createUser(
    name: 'Alice',
    email: 'alice@example.com',
    age: 30,
    admin: false,
  );
  final short = createUser(name: 'Bob', email: 'b', age: 1, admin: true);
  print([user, short, p.distanceTo(const Point(4, 6))]);
}

String createUser({
  required String name,
  required String email,
  required int age,
  required bool admin,
}) => '$name <$email>';

The rules: 2-space indentation, no tabs, lines up to 80 characters, and argument lists that don't fit get one argument per line with a trailing comma.

Since Dart 3.7 ("tall style"), the formatter decides about trailing commas itself. It added one to the createUser(name: 'Alice', ...) call because it was split, and removed the one in the Bob call because that fits on one line. Older formatters used a trailing comma you typed as a signal to split the list. If you want that behavior, or a different line width, configure it in analysis_options.yaml:

formatter:
  page_width: 100
  trailing_commas: preserve

With trailing_commas: preserve, makePoint(1, 2,) is kept split:

  final short = makePoint(
    1,
    2,
  );

The formatter only changes whitespace and commas. It doesn't add braces, so if you want braces on every if, enable the curly_braces_in_flow_control_structures lint. Effective Dart allows an if without braces when the whole statement fits on one line and there's no else.

In CI, check formatting without changing files. The exit code is 1 if any file would change:

$ dart format --output=none --set-exit-if-changed .
Changed a.dart
Formatted 1 file (1 changed) in 0.00 seconds.
$ echo $?
1

See Testing in CI for a full pipeline.

Idiomatic usage

Many conventions are about choosing the shortest clear way to write something. Here is code that compiles and works, checked with package:lints/recommended.yaml plus a few stricter rules (the configuration is at the end of the article):

class Animal {
  final String name;
  Animal(this.name);
}

class Dog extends Animal {
  Dog(String name) : super(name);
}

Future<void> save() async {}

void printAll(List<String> items) {
  items.forEach((item) {
    print(item);
  });
}

void connect(String host, bool secure) {}

String greet(String? name) {
  String result = "Hello, " + (name == null ? 'guest' : name);
  return result;
}

Future<void> run() async {
  save();
  var buffer = StringBuffer();
  buffer.write('a');
  buffer.write('b');
  print(buffer);
  var items = List<int>.empty(growable: true);
  items.addAll([1, 2]);
  if (items.length > 0) print(items);
  connect('example.com', true);
}

total(items) => items.length;
   info - before.dart:7:3 - Parameter 'name' could be a super parameter. Trying converting 'name' to a super parameter. - use_super_parameters
   info - before.dart:13:9 - Function literals shouldn't be passed to 'forEach'. Try using a 'for' loop. - avoid_function_literals_in_foreach_calls
   info - before.dart:13:17 - Closure should be a tearoff. Try using a tearoff rather than a closure. - unnecessary_lambdas
   info - before.dart:18:27 - 'bool' parameters should be named parameters. Try converting the parameter to a named parameter. - avoid_positional_boolean_parameters
   info - before.dart:21:3 - Local variables should be final. Try making the variable final. - prefer_final_locals
   info - before.dart:21:3 - Unnecessary type annotation on a local variable. Try removing the type annotation. - omit_local_variable_types
   info - before.dart:21:19 - Unnecessary use of double quotes. Try using single quotes unless the string contains single quotes. - prefer_single_quotes
   info - before.dart:21:19 - Use interpolation to compose strings and values. Try using string interpolation to build the composite string. - prefer_interpolation_to_compose_strings
   info - before.dart:21:32 - Use the '??' operator rather than '?:' when testing for 'null'. Try rewriting the code to use '??'. - prefer_if_null_operators
   info - before.dart:26:3 - Missing an 'await' for the 'Future' computed by this expression. Try adding an 'await' or wrapping the expression with 'unawaited'. - unawaited_futures
   info - before.dart:27:3 - Local variables should be final. Try making the variable final. - prefer_final_locals
   info - before.dart:28:3 - Unnecessary duplication of receiver. Try using a cascade to avoid the duplication. - cascade_invocations
   info - before.dart:31:3 - Local variables should be final. Try making the variable final. - prefer_final_locals
   info - before.dart:32:3 - Unnecessary duplication of receiver. Try using a cascade to avoid the duplication. - cascade_invocations
   info - before.dart:33:7 - Use 'isNotEmpty' instead of 'length' to test whether the collection is empty. Try rewriting the expression to use 'isNotEmpty'. - prefer_is_empty
   info - before.dart:37:1 - Missing type annotation on a public API. Try adding a type annotation. - type_annotate_public_apis
   info - before.dart:37:1 - Missing type annotation. Try adding a type annotation. - strict_top_level_inference
   info - before.dart:37:7 - Missing type annotation. Try adding a type annotation. - strict_top_level_inference

The same code following the conventions, with a main to run it:

class Animal {
  final String name;
  Animal(this.name);
}

class Dog extends Animal {
  Dog(super.name);
}

Future<void> save() async => print('saved');

void printAll(List<String> items) {
  items.forEach(print);
}

void connect(String host, {bool secure = true}) {
  print('${secure ? 'https' : 'http'}://$host');
}

String greet(String? name) {
  final result = 'Hello, ${name ?? 'guest'}';
  return result;
}

int total(List<Object?> items) => items.length;

Future<void> main() async {
  await save();
  final buffer = StringBuffer()
    ..write('a')
    ..write('b');
  print(buffer);
  final items = <int>[1, 2];
  if (items.isNotEmpty) print(items);
  connect('example.com', secure: false);
  print(greet(null));
  printAll(['x', 'y']);
  print(Dog('Rex').name);
  print(total(items));
}
saved
ab
[1, 2]
http://example.com
Hello, guest
x
y
Rex
2

The conventions behind these fixes:

Type annotations

Effective Dart's rule: annotate what's public, let inference handle what's local.

Collections

Use literals and the collection operators instead of constructors and loops that build a list:

final a = Map<String, int>();
final b = Set<int>();
final c = List<int>.from([1]).where((e) => e is int).toList();
final d = 'one ' +
    'two';
warning - bad_coll.dart:4:46 - Unnecessary type check; the result is always 'true'. Try correcting the type check, or removing the type check. - unnecessary_type_check
   info - bad_coll.dart:2:13 - Unnecessary constructor invocation. Try using a collection literal. - prefer_collection_literals
   info - bad_coll.dart:3:13 - Unnecessary constructor invocation. Try using a collection literal. - prefer_collection_literals
   info - bad_coll.dart:4:33 - Use 'whereType' to select elements of a given type. Try rewriting the expression to use 'whereType'. - prefer_iterable_wheretype
   info - bad_coll.dart:5:20 - String literals shouldn't be concatenated by the '+' operator. Try removing the operator to use adjacent strings. - prefer_adjacent_string_concatenation

The idiomatic versions: <String, int>{}, <int>{}, whereType<int>(), adjacent string literals, and collection if, for and spread (...) inside literals:

List<String> buildArgs({required bool verbose, List<String> files = const []}) {
  return [
    'compile',
    if (verbose) '--verbose',
    for (final f in files) '--input=$f',
    ...['-o', 'out'],
  ];
}

void main() {
  print(buildArgs(verbose: true, files: ['a.dart', 'b.dart']));
  print(buildArgs(verbose: false));

  final mixed = <Object?>[1, 'two', null, 3];
  print(mixed.whereType<int>().toList());

  const message =
      'Adjacent string literals are joined at compile time, '
      'so long text needs no + operator.';
  print(message);
}
[compile, --verbose, --input=a.dart, --input=b.dart, -o, out]
[compile, -o, out]
[1, 3]
Adjacent string literals are joined at compile time, so long text needs no + operator.

Test for emptiness with isEmpty and isNotEmpty, never length == 0; for some iterables computing length means walking all elements.

Classes: fields, getters and setters

Unlike Java, Dart doesn't need getters and setters to protect fields. A public field can later be replaced with a getter/setter pair without changing any code that uses it, so start with a plain field:

class Temperature {
  double _celsius = 0;

  double get celsius => _celsius;
  set celsius(double value) {
    _celsius = value;
  }
}
   info - gs.dart:4:14 - Unnecessary use of getter and setter to wrap a field. Try removing the getter and setter and renaming the field. - unnecessary_getters_setters

Write getters for computed values, and setters only when there's a matching getter:

class Temperature {
  Temperature(this.celsius);

  double celsius;

  double get fahrenheit => celsius * 9 / 5 + 32;
  set fahrenheit(double value) => celsius = (value - 32) * 5 / 9;

  bool get isFreezing => celsius <= 0;

  Temperature copyWith({double? celsius}) =>
      Temperature(celsius ?? this.celsius);

  @override
  String toString() => '${celsius.toStringAsFixed(1)} °C';
}

void main() {
  final t = Temperature(25);
  print('$t = ${t.fahrenheit} °F, freezing: ${t.isFreezing}');
  t.fahrenheit = 14;
  print('$t, freezing: ${t.isFreezing}');
  print(t.copyWith(celsius: 100));
}
25.0 °C = 77.0 °F, freezing: false
-10.0 °C, freezing: true
100.0 °C

Other class conventions:

More about this in Getters and Setters.

Async style

Prefer async/await to chains of then. Both functions below do the same thing:

Future<String> fetchUser(int id) async => 'user$id';
Future<int> fetchScore(String user) async => user.length * 10;

// Harder to read: nested callbacks
Future<void> reportWithThen(int id) {
  return fetchUser(id)
      .then((user) {
        return fetchScore(user).then((score) {
          print('$user: $score');
        });
      })
      .catchError((Object e) {
        print('failed: $e');
      });
}

// Preferred: async/await with try/catch
Future<void> report(int id) async {
  try {
    final user = await fetchUser(id);
    final score = await fetchScore(user);
    print('$user: $score');
  } on FormatException catch (e) {
    print('failed: $e');
  }
}

Future<void> main() async {
  await reportWithThen(1);
  await report(42);
}
user1: 50
user42: 60

The await version reads top to bottom, and try/catch with on clauses catches only the errors you expect. See Async and Await.

Comments and documentation

/// Parses [input] as a duration such as `90s`, `5m` or `2h`.
///
/// Throws a [FormatException] if [input] has no known unit suffix.
Duration parseDuration(String input) {
  final value = int.parse(input.substring(0, input.length - 1));
  return switch (input[input.length - 1]) {
    's' => Duration(seconds: value),
    'm' => Duration(minutes: value),
    'h' => Duration(hours: value),
    _ => throw FormatException('Unknown unit', input),
  };
}

parseDuration('90s') returns 0:01:30.000000. See Documentation using Dartdoc for generating HTML docs.

A stricter analysis_options.yaml

package:lints/recommended.yaml is a good minimum (Flutter projects use package:flutter_lints, which builds on it). The examples in this article were checked with a few extra rules that enforce the conventions above:

include: package:lints/recommended.yaml

formatter:
  page_width: 80

linter:
  rules:
    - directives_ordering
    - prefer_final_locals
    - prefer_single_quotes
    - omit_local_variable_types
    - type_annotate_public_apis
    - avoid_positional_boolean_parameters
    - unawaited_futures
    - unnecessary_lambdas
    - use_super_parameters
    - cascade_invocations

Some well-known rules contradict each other (prefer_double_quotes vs prefer_single_quotes, always_specify_types vs omit_local_variable_types), so pick rules individually instead of enabling everything. For library packages, also consider public_member_api_docs, which requires a doc comment on every public member. Popular stricter rule sets published as packages include very_good_analysis.

To silence a lint in one place, use an ignore comment with the rule name, and say why. Here the opt-in avoid_print rule (enabled by package:flutter_lints) is suppressed:

// ignore: avoid_print, this is a command-line tool and print is its output
print(report);

Use // ignore_for_file: rule_name at the top of generated files. For the type-safety settings strict-casts, strict-inference and strict-raw-types, see the last section of Common pitfalls.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents