AvoidUncaughtFutureErrorsRule class
Warns when fire-and-forget Future lacks error handling.
Since: v2.0.0 | Updated: v4.13.0 | Rule version: v5
Alias: require_future_error_handling, catch_future_errors, future_error_handler, handle_future_exception, unhandled_future, fire_and_forget_future, add_catch_error
When a Future is called without awaiting ("fire and forget"), any errors it throws go to the global error handler or are silently lost. This rule detects unawaited Futures that lack error handling.
Note: Awaited futures are NOT flagged because await propagates errors
to the enclosing async function's Future - that's proper Dart error handling.
BAD - Unhandled fire-and-forget
void initState() {
super.initState();
loadData(); // Future errors are lost!
}
void _onTap() {
_pageController.nextPage(...); // Errors silently ignored
}
GOOD - Handle or explicitly acknowledge
// Option 1: Add try-catch to the async function (RECOMMENDED)
// If the function has internal try-catch, this lint won't flag calls to it.
Future<void> _loadData() async {
try {
await fetchFromApi();
} on Exception catch (e, s) {
debugException(e, s);
}
}
// Option 2: Use .ignore() for intentional fire-and-forget
// Best for SDK methods like PageController, AnimationController, etc.
_pageController.nextPage(...).ignore();
_animationController.forward().ignore();
// Option 3: Use unawaited() from dart:async
// Explicit acknowledgment that you don't care about the result or errors.
unawaited(analytics.logEvent('button_pressed'));
// Option 4: Add .catchError() at the call site
loadData().catchError((e, s) {
debugPrint('$e\n$s');
return null;
});
When to use .ignore() vs unawaited()
.ignore()- Preferred for method chains, cleaner syntaxunawaited()- Fromdart:async, wraps the entire expression
Both explicitly acknowledge that you're intentionally ignoring the Future.
Expression statements that are exactly a call to unawaited(...) are
never reported, as they explicitly acknowledge fire-and-forget.
Developer note: The rule skips by checking the statement's expression
for a top-level MethodInvocation with method name unawaited before any
type resolution or chain walking, so unawaited(...); is never reported
in all analyzer/code paths.
Exceptions (not flagged)
- Futures with
.catchError()chained - Futures with
.then(onError: ...)callback - Futures with
.ignore()chained - explicit acknowledgment - Futures wrapped in
unawaited()- explicit acknowledgment - Safe fire-and-forget methods:
cancel(),close(),dispose(),drain() - Analytics methods:
logEvent(),trackEvent(),setCurrentScreen() - Cache operations:
prefetch(),preload(),warmCache(),invalidate() - Futures inside
dispose()methods - synchronous context can't await - Futures already inside a try block
- Functions defined in the same file that have try-catch in their body
Limitation: Cross-file analysis
This rule can only detect try-catch in functions defined in the same file.
If you call a method from another file that has internal error handling (e.g.,
propagating errors via StreamController.addError()), this rule cannot detect
that. Use // ignore: avoid_uncaught_future_errors with an explanatory comment
or .ignore() for these cases.
Quick fixes available:
- Add
.catchError()withdebugPrint - Add
// ignore:comment
- Inheritance
-
- Object
- SaropaLintRule
- AvoidUncaughtFutureErrorsRule
Constructors
Properties
- accuracyTarget → AccuracyTarget?
-
Optional accuracy target for this rule (for documentation and tooling).
Does not enforce; used by reports and rule-audit scripts.
no setterinherited
-
applicableFileTypes
→ Set<
FileType> ? -
The file types this rule applies to.
no setterinherited
- canUseParsedResult → bool
-
Indicates whether this analysis rule can work with just the parsed
information or if it requires a resolved unit.
no setterinherited
-
certIds
→ List<
String> -
CERT coding standard identifiers (e.g. STR02-C). Populate only where
there is a clear mapping; leave empty for most rules initially.
no setterinherited
- code → LintCode
-
The lint code for this rule.
no setterinherited
-
configAliases
→ List<
String> -
Alternate config keys that can be used to reference this rule.
no setterinherited
-
conflictingRules
→ List<
String> -
Curated opposite/competing rule names.
no setterinherited
- cost → RuleCost
-
The estimated execution cost of this rule.
no setteroverride
-
cweIds
→ List<
int> -
CWE identifiers this rule helps prevent or detect.
https://cwe.mitre.org/ — e.g. CWE-798 (Hardcoded Credentials).
no setterinherited
- description → String
-
Short description suitable for display in console output and IDEs.
finalinherited
- diagnosticCode → DiagnosticCode
-
The code to report for a violation.
no setterinherited
-
diagnosticCodes
→ List<
DiagnosticCode> -
The diagnostic codes associated with this analysis rule.
no setterinherited
- documentationUrl → String
-
Returns the documentation URL for this rule.
no setterinherited
- effectiveSeverity → DiagnosticSeverity?
-
Get the effective severity for this rule, considering overrides.
no setterinherited
- exampleBad → String?
-
Short code example that VIOLATES this rule (shown in CLI walkthrough).
no setterinherited
- exampleGood → String?
-
Short code example of COMPLIANT code (shown in CLI walkthrough).
no setterinherited
-
fixGenerators
→ List<
SaropaFixGenerator> -
Fix producer generators for this rule.
no setterinherited
- hashCode → int
-
The hash code for this object.
no setterinherited
- hyphenatedName → String
-
Returns the rule name in hyphenated format for display.
no setterinherited
- impact → LintImpact
-
The business impact of this rule's violations.
no setteroverride
-
incompatibleRules
→ List<
String> -
A list of incompatible rule names.
no setterinherited
- isDisabled → bool
-
Check if this rule is disabled via configuration.
no setterinherited
- maximumLineCount → int
-
Maximum line count for this rule to run.
no setterinherited
- minimumLineCount → int
-
Minimum line count for this rule to run.
no setterinherited
- name → String
-
The rule name.
finalinherited
- owasp → OwaspMapping?
-
OWASP categories this rule helps prevent.
no setterinherited
- pubspecVisitor → PubspecVisitor?
-
A visitor that visits a
Pubspecto perform analysis.no setterinherited -
Curated "see also" rule names for discoverability in docs/IDE tooling.
no setterinherited
- reporter ← DiagnosticReporter
-
Sets the
DiagnosticReporterfor theCompilationUnitcurrently being visited.no getterinherited -
requiredPatterns
→ Set<
String> ? -
String patterns that must be present in the file for this rule to run.
no setterinherited
- requiresAsync → bool
-
Whether this rule only applies to async code.
no setterinherited
- requiresBlocImport → bool
-
Whether this rule only applies to files that import Bloc.
no setterinherited
- requiresClassDeclaration → bool
-
Whether this rule only applies to files with class declarations.
no setterinherited
- requiresFlutterImport → bool
-
Whether this rule only applies to files that import Flutter.
no setterinherited
- requiresImports → bool
-
Whether this rule only applies to files with imports.
no setterinherited
- requiresMainFunction → bool
-
Whether this rule only applies to files with a main() function.
no setterinherited
- requiresProviderImport → bool
-
Whether this rule only applies to files that import Provider.
no setterinherited
- requiresRiverpodImport → bool
-
Whether this rule only applies to files that import Riverpod.
no setterinherited
- requiresWidgets → bool
-
Whether this rule only applies to Flutter widget code.
no setterinherited
- ruleStatus → RuleStatus
-
Lifecycle status. Default RuleStatus.ready. Use RuleStatus.beta for
new or heuristic-heavy rules; RuleStatus.deprecated for sunset.
no setterinherited
- ruleType → RuleType?
-
Semantic type of this rule. Default
null= unspecified (legacy). When set, used for quality gates, accuracy targets, and reporting.no setteroverride - runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- skipExampleFiles → bool
-
Whether to skip example files (example/**).
no setterinherited
- skipFixtureFiles → bool
-
Whether to skip fixture files (fixture/, fixtures/).
no setterinherited
- skipGeneratedCode → bool
-
Whether to skip generated files (*.g.dart, *.freezed.dart, *.gen.dart).
no setterinherited
- skipTestFiles → bool
-
Whether to skip test files (*_test.dart, test/**).
no setterinherited
- state → RuleState
-
The state of this analysis rule.
finalinherited
-
supersedesRules
→ List<
String> -
Rule names this rule supersedes/replaces.
no setterinherited
-
Tags for filtering and discovery (e.g. in docs, IDE, or CI).
Examples: 'performance', 'accessibility', 'suspicious', 'convention'.
no setteroverride
- testRelevance → TestRelevance
-
How this rule relates to test files.
no setterinherited
- usesTypeResolution → bool
-
Whether this rule triggers lazy cross-library type resolution in the
analyzer (e.g.
.staticType,.library,.allSupertypes,.enclosingElement).no setteroverride
Methods
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
registerNodeProcessors(
RuleVisitorRegistry registry, RuleContext context) → void -
Registers node processors in the given
registry.inherited -
reportAtNode(
AstNode? node, {List< Object> arguments = const [], List<DiagnosticMessage> ? contextMessages}) → Diagnostic? -
Reports a diagnostic at
nodewith messageargumentsandcontextMessages.inherited -
reportAtOffset(
int offset, int length, {List< Object> arguments = const [], List<DiagnosticMessage> ? contextMessages}) → Diagnostic -
Reports a diagnostic at
offset, withlength, with messageargumentsandcontextMessages.inherited -
reportAtPubNode(
PubspecNode node, {List< Object> arguments = const [], List<DiagnosticMessage> contextMessages = const []}) → Diagnostic -
Reports a diagnostic at Pubspec
node, with messageargumentsandcontextMessages.inherited -
reportAtSourceRange(
SourceRange sourceRange, {List< Object> arguments = const [], List<DiagnosticMessage> ? contextMessages}) → Diagnostic -
Reports a diagnostic at
sourceRange, with messageargumentsandcontextMessages.inherited -
reportAtToken(
Token token, {List< Object> arguments = const [], List<DiagnosticMessage> ? contextMessages}) → Diagnostic? -
Reports a diagnostic at
token, with messageargumentsandcontextMessages.inherited -
runWithReporter(
SaropaDiagnosticReporter reporter, SaropaContext context) → void -
Override this method to implement your lint rule.
override
-
shouldSkipFile(
String path) → bool -
Check if a file path should be skipped based on context settings.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited