Rules / Correctness / proper-super-init-state

proper-super-init-state

lint/correctness/proper-super-init-state
recommendedflutter
Same as proper_super_init_state · Pyramid Lint

Require super.initState() to be the first call in initState.

Flags an initState method whose first statement is not super.initState(), whether the call comes later or is missing altogether. The framework's State.initState establishes the base bookkeeping the object depends on, so a subclass must let it run before its own setup; initialization that touches context or framework state before super.initState() runs against an object that is not yet fully wired. Make super.initState() the first line of the method.

Invalid

example.dartdart
import 'package:flutter/material.dart';

class A extends State<StatefulWidget> {
  @override
  void initState() {
    doStuff();
    super.initState();
  }
}

class B extends State<StatefulWidget> {
  int x = 0;

  @override
  void initState() {
    x = 1;
  }
}

class C extends State<StatefulWidget> {
  @override
  void initState() {}
}

class D extends ConsumerState<StatefulWidget> {
  @override
  void initState() {
    final a = 1;
    super.initState();
    print(a);
  }
}

class E extends State<StatefulWidget> {
  @override
  void initState() {
    setup();
    super.initState();
  }
}
super.initState() should be called first in initState().
6 doStuff();
7 super.initState();
super.initState() should be called first in initState().
14 @override
15 void initState() {
super.initState() should be called first in initState().
21 @override
22 void initState() {}
super.initState() should be called first in initState().
28 final a = 1;
29 super.initState();
super.initState() should be called first in initState().
37 setup();
38 super.initState();

Valid

example.dartdart
import 'package:flutter/material.dart';

class A extends State<StatefulWidget> {
  @override
  void initState() {
    super.initState();
    doStuff();
  }
}

class B extends State<StatefulWidget> {
  @override
  void initState() {
    super.initState();
  }
}

class C extends ConsumerState<StatefulWidget> {
  @override
  void initState() {
    super.initState();
    final a = 1;
    print(a);
  }
}

class D {
  void initState() {
    doStuff();
  }
}

class E extends StatelessWidget {
  void initState() {}
}

How to configure

Set the severity of proper-super-init-state in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "correctness": {
        "proper-super-init-state": "error"
      }
    }
  }
}