Question #154MediumDart Basics

Flutter linter rules?

#flutter#dart

Answer

Overview

Flutter linter rules in

text
analysis_options.yaml
enforce code style, catch potential bugs, and promote best practices. They are checked by the Dart analyzer in real-time as you type.


Setup

yaml
# analysis_options.yaml (project root)
include: package:flutter_lints/flutter.yaml  # Flutter's recommended set

analyzer:
  strong-mode:
    implicit-casts: false
    implicit-dynamic: false
  errors:
    missing_required_param: error
    missing_return: error

linter:
  rules:
    # Style rules
    - prefer_const_constructors
    - prefer_const_declarations
    - sort_child_properties_last
    - always_use_package_imports

    # Bug prevention
    - avoid_print
    - cancel_subscriptions
    - close_sinks
    - unawaited_futures

    # Null safety
    - avoid_null_checks_in_equality_operators

    # Performance
    - avoid_unnecessary_containers
    - sized_box_for_whitespace

Common Linter Rules

Performance Rules

dart
// avoid_unnecessary_containers
// ❌
Container(child: Text('Hello'));

// ✅
Text('Hello'); // No Container if no decoration

// sized_box_for_whitespace
// ❌
Container(height: 16);
// ✅
SizedBox(height: 16);

Code Quality Rules

dart
// prefer_const_constructors
// ❌ — runtime allocation
Text('Hello');
// ✅ — compile-time, reused
const Text('Hello');

// avoid_print (use debugPrint or logger)
// ❌
print('Debug info');
// ✅
debugPrint('Debug info');

Null Safety Rules

dart
// prefer_if_null_operators
// ❌
final name = user != null ? user.name : 'Guest';
// ✅
final name = user?.name ?? 'Guest';

Popular Rule Packages

yaml
# pubspec.yaml
dev_dependencies:
  flutter_lints: ^3.0.0       # Flutter's default (recommended)
  very_good_analysis: ^5.1.0  # Strict rules (Very Good Ventures)
  lint: ^2.1.2                 # Community rules
yaml
# Include a predefined set
include: package:very_good_analysis/analysis_options.yaml

Common Rules Reference

RuleDescription
text
prefer_const_constructors
Use const for widgets
text
avoid_print
Use debugPrint instead
text
cancel_subscriptions
Cancel StreamSubscription in dispose
text
close_sinks
Close StreamControllers
text
unawaited_futures
Don't ignore Future return values
text
sort_child_properties_last
text
child:
last in widget
text
prefer_single_quotes
Use
text
'
over
text
"
text
always_declare_return_types
No implicit return types

Best Practice: Start with

text
package:flutter_lints/flutter.yaml
and add rules incrementally. Run
text
dart analyze
in CI to enforce rules on every PR.