dart-fix-static-analysis-errors
Resolving Dart Static Analysis Errors
Contents
- Diagnostic Execution
- Null Safety & Type Resolution
- Flow Analysis & Type Promotion
- Analyzer Configuration
- Workflow: Static Analysis Remediation
- Examples
Diagnostic Execution
Execute the Dart analyzer to identify static errors, warnings, and informational diagnostics across the codebase.
- Run
$ dart analyzeto evaluate all Dart files in the current directory. - Target specific directories or files by appending the path:
$ dart analyze binor$ dart analyze lib/main.dart. - Enforce strictness by failing on info-level issues using the
--fatal-infosflag. - Apply automated quick-fixes for supported diagnostics using
$ dart fix --apply. Preview changes first with$ dart fix --dry-run.
Null Safety & Type Resolution
Address static errors related to Dart's sound null safety and strict type system.
- Nullability: Append
?to types to explicitly allownull(e.g.,String?). - Assertion: Use the postfix bang operator
!to cast a nullable expression to its underlying non-nullable type when you can guarantee it is not null. - Delayed Initialization: Apply the
latemodifier to non-nullable top-level or instance variables that are guaranteed to be initialized before their first read, bypassing the analyzer's definite assignment checks. - Named Parameters: Use the
requiredmodifier for named parameters that do not have a default value and cannot be null. - Explicit Downcasts: If static analysis disallows an implicit downcast (e.g., assigning
List<Animal>toList<Cat>), use an explicit cast:as List<Cat>. - Generic Types: Always provide explicit type annotations to generic classes (e.g.,
List<String>,Map<String, dynamic>). Avoid using a rawListorMapwhich defaults todynamic.
Flow Analysis & Type Promotion
Leverage Dart's control flow analysis to safely promote nullable types to non-nullable types without manual casting.
- Null Checks: Check a local variable against
null(e.g.,if (value != null)) to automatically promote it to a non-nullable type within that block. - Type Tests: Use the
isoperator (e.g.,if (value is String)) to promote a variable to a specific subclass or type. - Early Returns: Use early returns,
break, orthrowto exit a control flow path if a variable is null or the wrong type. The analyzer will promote the variable for the remainder of the scope. - Reachability: Use the
Nevertype for functions that unconditionally throw exceptions or terminate the process. The analyzer uses this to determine unreachable code paths.
Analyzer Configuration
Configure the analysis_options.yaml file at the package root to enforce stricter type checks and customize linter rules.
- Enable
strict-casts: trueto prevent implicit downcasts fromdynamic. - Enable
strict-inference: trueto prevent the analyzer from falling back todynamicwhen it cannot infer a type. - Enable
strict-raw-types: trueto require explicit type arguments on generic types. - Suppress specific diagnostics in a file using
// ignore_for_file: <diagnostic_name>. - Suppress a diagnostic on a specific line using
// ignore: <diagnostic_name>.
Workflow: Static Analysis Remediation
Follow this sequential workflow to resolve static analysis errors in a Dart project.
Task Progress Checklist
Copy this checklist to track your progress:
- Run
$ dart analyzeto establish a baseline of errors. - Run
$ dart fix --applyto resolve automatically fixable issues. - Address remaining Null Safety errors (
?,!,late,required). - Address remaining Type System errors (explicit
ascasts, generic type annotations). - Run
$ dart analyzeto verify all errors are resolved. - Execute tests or run the application to ensure fixes did not introduce runtime exceptions (e.g., failed
ascasts or uninitializedlatevariables).
Conditional Logic
- If working with mixed-version code (legacy Dart 2.9): Disable sound null safety temporarily by passing
--no-sound-null-safetytodart runorflutter run, or by adding// @dart=2.9to the top of the entrypoint file. - If a field is private and final: Rely on flow analysis for type promotion.
- If a field is public or non-final: Flow analysis cannot promote it. Copy the field to a local variable first, check the local variable for null, and use the local variable.
Feedback Loop
- Run Validator:
$ dart analyze - Review Errors: Identify the file, line number, and diagnostic code.
- Fix: Apply the appropriate null safety or type resolution fix.
- Repeat: Continue until
$ dart analyzereturns "No issues found!".
Examples
Type Promotion via Local Variable Assignment
When dealing with nullable instance fields, copy to a local variable to enable flow analysis.
Incorrect (Fails Analysis):
class Coffee {
String? _temperature;
void checkTemp() {
if (_temperature != null) {
// ERROR: Property cannot be promoted because it is not a local variable.
print(_temperature.length);
}
}
}
Correct:
class Coffee {
String? _temperature;
void checkTemp() {
final temp = _temperature; // Copy to local variable
if (temp != null) {
// SUCCESS: 'temp' is promoted to non-nullable String.
print(temp.length);
}
}
}
Strict Analyzer Configuration
Implement the following analysis_options.yaml to enforce strict type safety.
include: package:lints/recommended.yaml
analyzer:
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
errors:
invalid_assignment: error
missing_return: error
dead_code: info
More from dart-lang/skills
dart-use-pattern-matching
Use switch expressions and pattern matching where appropriate
954dart-resolve-package-conflicts
Workflow for fixing package version conflicts. Use this when `pub get` fails due to incompatible package versions.
948dart-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.
948dart-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.
948dart-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.
945dart-collect-coverage
Collect coverage using the coverage packge and create an LCOV report
942