dart-language-syntax
Writing Idiomatic Dart
Contents
- Variables and State Management
- Functions and Closures
- Records and Pattern Matching
- Generics and Type Safety
- Workflow: Refactoring to Idiomatic Dart
- Examples
Variables and State Management
Manage state and variable declarations using strict mutability and type inference rules.
- Prefer
var: Usevarfor local variables when the assigned type is obvious (e.g.,var name = 'Bob';). Use explicit types when the type is not immediately clear from the initializer. - Enforce Immutability: Use
finalfor variables that should not be reassigned after initialization. Useconstfor compile-time constants and to create canonicalized, immutable object instances. - Leverage
late: Use thelatemodifier to defer initialization of non-nullable variables until their first use, especially for expensive computations or when initialization requires access tothis. - Implement Wildcards: Use the wildcard variable
_(requires Dart 3.7+) to discard unused values in local declarations, closures, or pattern matching without triggering unused variable warnings.
Functions and Closures
Structure functions for maximum composability and minimal boilerplate.
More from dart-lang/skills
dart-add-unit-test
Write and organize unit tests for functions, methods, and classes using `package:test`. Use when creating new logic or fixing bugs to ensure code remains correct and regression-free.
2.1Kdart-fix-runtime-errors
Uses get_runtime_errors and lsp to fetch an active stack trace, locate the failing line, apply a fix, and verify resolution via hot_reload.
2.1Kdart-run-static-analysis
Execute `dart analyze` to identify warnings and errors, and use `dart fix --apply` to automatically resolve mechanical lint issues. Use during development to ensure code quality and before committing changes.
2.1Kdart-use-pattern-matching
Use switch expressions and pattern matching where appropriate
2.1Kdart-resolve-package-conflicts
Workflow for fixing package version conflicts. Use this when `pub get` fails due to incompatible package versions.
2.1Kdart-collect-coverage
Collect coverage using the coverage packge and create an LCOV report
2.0K