dart-async-programming
Writing Asynchronous Dart Code
Contents
Core Guidelines
Write asynchronous Dart code using modern, declarative patterns. Avoid legacy callback-based approaches. Assume all network, file I/O, and database operations are asynchronous.
- Use
async/await: Always preferasyncandawaitover raw.then(),.catchError(), or.whenComplete()chains. This flattens the execution flow and improves readability. - Handle Errors Gracefully: Wrap all
awaitcalls intry-catchblocks to handle exceptions. Do not rely on unhandled future rejections. - Execute Concurrently: Use
Future.waitto initiate and await multiple independent futures concurrently rather than awaiting them sequentially. - Consume Streams Sequentially: Prefer
await forover.forEach()or.listen()when consuming streams, unless you specifically need low-level subscription management (like pausing or resuming). - Prevent Memory Leaks: Always call
.close()on aStreamControllerwhen it is no longer needed or when the owning class is disposed.
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.0Kdart-use-pattern-matching
Use switch expressions and pattern matching where appropriate
2.0Kdart-resolve-package-conflicts
Workflow for fixing package version conflicts. Use this when `pub get` fails due to incompatible package versions.
2.0Kdart-collect-coverage
Collect coverage using the coverage packge and create an LCOV report
2.0K