dart-fix-runtime-errors
Uses static analysis diagnostics and custom handling patterns for null safety, dynamic lists, contravariance overrides, and unrecoverable errors.
What this skill does
## Contents
- [Type System and Soundness](#type-system-and-soundness)
- [Null Safety and Variable Initialization](#null-safety-and-variable-initialization)
- [Error and Exception Handling](#error-and-exception-handling)
- [Workflow: Resolving Static Analysis and Runtime Failures](#workflow-resolving-static-analysis-and-runtime-failures)
- [Examples](#examples)
## Type System and Soundness
Dart enforces a sound type system to ensure that variables match their compile-time types at runtime. To prevent runtime type errors:
- **Method Overrides**: Ensure subclass overrides maintain covariant return types and contravariant parameter types. Never tighten parameter types in a subclass unless explicitly using the `covariant` keyword to override safety checks.
- **Generics and Collection Types**: Avoid assigning untyped collections (like `List<dynamic>`) directly to strongly typed targets. Always provide explicit generic parameters (e.g. `List<String>`) during list or map initialization.
- **Explicit Downcasting**: Avoid implicit downcasts from `dynamic` values. Use explicit type casting (e.g. `as List<Map<String, dynamic>>`) only when the underlying structure is guaranteed to match.
- **Strict Configuration**: Enable strict casting configurations in your project's `analysis_options.yaml` to enforce explicit casts and catch dynamic typing bugs during code analysis:
```yaml
analyzer:
language:
strict-casts: true
```
## Null Safety and Variable Initialization
Properly manage variable states to avoid compile-time analyzer errors and runtime null pointer exceptions:
- **Nullable Indicators**: Append `?` to types that are permitted to hold null values. Use `!` only when asserting that a value is definitively non-null.
- **Late Initialization**: Apply the `late` keyword only when the variable is guaranteed to be initialized before its first access. If a late variable is accessed before initialization, a `LateInitializationError` is thrown at runtime.
- **Wildcard Variables**: Use a single underscore `_` (supported in modern Dart versions) to declare local parameters or variables that are intentionally unread, satisfying unused variable lints.
## Error and Exception Handling
Distinguish between recoverable app failures (Exceptions) and unrecoverable bugs (Errors):
- **Catching Exceptions**: Implement try-catch blocks to catch and handle subclasses of `Exception` (e.g. `FormatException`, `SocketException`). These represent expected runtime failures that the application should handle gracefully.
- **Avoid Catching Errors**: Do not catch `Error` or its subclasses (e.g. `TypeError`, `RangeError`). Errors represent coding bugs that must be corrected during development, not suppressed at runtime.
- **Rethrowing**: When catching an exception to perform logging or cleanup, always use the `rethrow` keyword instead of throwing the caught exception again. `rethrow` preserves the original stack trace.
## Workflow: Resolving Static Analysis and Runtime Failures
Follow this checklist to identify, correct, and verify static and runtime bugs:
- [ ] **Run static analyzer**: Execute `dart analyze . --fatal-infos` in the project root.
- [ ] **Apply automated fixes**: Preview and apply mechanical adjustments using:
```bash
dart fix --dry-run
dart fix --apply
```
- [ ] **Identify manual fixes**: Address complex warnings:
- If a nullability conflict is reported: Assess the business logic, specify defaults using the coalescing operator `??`, or use the null-aware chain `?.`.
- If a covariant mismatch is reported: Adjust subclass parameters or apply the `covariant` modifier.
- [ ] **Test execution**: Run `dart test` or `flutter test` to ensure runtime soundness.
- [ ] **Verify late state changes**: Inspect stack traces if a `TypeError` or `LateInitializationError` occurs at runtime, correcting initialization flows.
## Examples
### Correcting Dynamic List Assignments
```dart
// Fails Static Analysis due to List<dynamic> assignment:
void printScores(List<int> scores) => print(scores);
void badMain() {
final scores = []; // Inferred as List<dynamic>
scores.add(90);
printScores(scores); // Error: List<dynamic> cannot be assigned to List<int>
}
// Corrected Implementation:
void goodMain() {
final scores = <int>[]; // Explicitly typed
scores.add(90);
printScores(scores); // Compiles and runs safely
}
```
### Method Overrides and Covariants
```dart
class Worker {
void performTask(Task t) {}
}
// Fails Static Analysis: Tightening parameter type from Task to CodingTask
class SoftwareEngineer extends Worker {
@override
void performTask(CodingTask t) {}
}
// Corrected Implementation using the covariant keyword:
class LeadSoftwareEngineer extends Worker {
@override
void performTask(covariant CodingTask t) {}
}
```
### Safely Managing Late Initializations
```dart
class DatabaseClient {
// Late keyword defers null safety checks to runtime
late final String connectionString;
void initialize(String url) {
connectionString = url;
}
void connect() {
// If connect() is called before initialize(), this throws a LateInitializationError
print('Connecting to $connectionString');
}
}
```
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.