Dart Style Guide (WIP)

Overview

This is the style guide for Autonomy for all Dart code, based off:

If you are uncertain, refer to Effective Dart documentation or asks the Autonomy leads for help.

 

Dart Linter

 

Files

Name packages, directories, and source files using snake_case:

my_package └─ lib └─ file_system.dart └─ slider_menu.dart

File contents end with 1 blank line:

Amazing dart code... // Last blank line below, then end of file

 

Indentation

 

Imports

  • One space between each import level

  • Sort each import section alphabetically

Import order:

  1. System-level imports: Anything that starts with import 'dart:__'

  2. Installed packages: Anything that starts with import 'package:__'

  3. Local packages: Anything written by/for WARG (including submodules)

Name import prefixes using snake_case:

import 'dart:math' as math; import 'package:angular_components/angular_components.dart' as angular_components; import 'package:js/js.dart' as js; import 'util.dart';

 

Identifier naming

  • variableNames in lowerCamelCase

  • constantNames in lowerCamelCase

  • functionNames in lowerCamelCase

  • Classes, enumerated types, typedefs and type parameters should be in UpperCamelCase

 

Variables

  • use final for local variables that are not re-assigned

 

Classes

  • Private members (methods and attributes) are prefixed with 1 underscore

  • Initialize fields at their declaration when possible

 

 

Logic

  • Use curly braces for all flow control statements

    • Exception: if statement with no else clause and whole if statement fits on one line, can omit braces

  • Put subsequent if and else on the same line as previous block’s closing brace

  • Avoid using true or false in equality operations

 

Functions

  • Use = to separate parameters from its default value

 

Operators

  • No spaces around : if it's used as a slicing operator, otherwise space after:

  • One space on either side of all binary operators, including assignment operators

    • Ex: + - * / % , += -= *= /=, > < == !=

  • One space after every comma

Strings

  • Use adjacent strings to concatenate string literals

  • Use interpolation to combine string and values

    • Avoid curly braces when not necessary

Misc

  • Lines are 100 characters long

  • No spaces at the end of a line

Multiline

 

Commenting

Format comments like sentences

Doc comments TODO: investigate dart doc

  • use /// to document members and types

  • Dart doc can find & generate comments for it

  • Start doc comments with single-sentence summary

  • Separate first sentence from rest of description

General Example

 

 

No commented out and unreachable code

Do not add code that you have commented out. It is better to just delete it. Git and GitHub will keep a record if it’s ever needed again.

Additionally, delete unreachable code (code that will never be run). For example: