Skip to content

Proposal: initialize fields at the declaration site #153644

@nate-thegrate

Description

@nate-thegrate

before

class _MyState extends State<MyWidget> with SingleTickerProviderMixin {
  late final int _value;
  AnimationController? _controller;

  @override
  void initState() {
    _value = widget.value;
    _controller = AnimationController(
      duration: Durations.medium1,
      vsync: this,
    );
  }

  // ...
}

after

class _MyState extends State<MyWidget> with SingleTickerProviderMixin {
  late final int _value = widget.value;

  late final AnimationController _controller = AnimationController(
    duration: Durations.medium1,
    vsync: this,
  );

  // ...
}

This has a few advantages:

  1. More concise
  2. Less jumping around to see how fields are initialized
  3. Less prone to late initialization errors
  4. The prefer final & unnecessary nullable lints will kick in

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectc: proposalA detailed proposal for a change to Flutterc: tech-debtTechnical debt, code quality, testing, etc.frameworkflutter/packages/flutter repository. See also f: labels.refactorImproving readability/efficiency without behavioral changesteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions