Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should codes be written before super.initState(); or after in Flutter?

Tags:

flutter

dart

Should the code that is being written to initState() function be written before super.initState(); or after?

Which one is proper:

  @override
    // code here
    super.initState();
  }

or

  @override
    super.initState();
    // code here
  }
like image 429
kamranbekirovyz Avatar asked Feb 17 '20 00:02

kamranbekirovyz


People also ask

Where do you write initState in flutter?

Flutter – initSate() The initState() is a method that is called when an object for your stateful widget is created and inserted inside the widget tree. It is basically the entry point for the Stateful Widgets.

Where do I put super initState?

super. initState() should always be the first line in your initState method.

How do you initState in flutter?

initState method Null safetyThe framework will call this method exactly once for each State object it creates. Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).

Why is initState called twice?

This is a combination of two facts: each route is entirely independent. / do not share state with /login , therefore going from / to /login will trigger an initState on the LoginPage from /login . initialRoute: '/login' does not mean that the app starts directly on /login .


1 Answers

both will work.

But if you see from any dependencies or official docs flutter, write your code in initSate() after super.initState();

@overrride
initState(){
  super.initState()
  //your code
}

reference to this initState

the opposite for dispose(), write your code before super.dispose();

@overrride
dispose(){
  //your code
  super.dispose()
}

reference to dispose

When I see @Kahoo answer, I check it by cmd + click at super.dispose and super.initstate, I found this for dispose

  /// If you override this, make sure to end your method with a call to
  /// super.dispose().
  ///
  /// See also:
  ///
  ///  * [deactivate], which is called prior to [dispose].
  @protected
  @mustCallSuper
  void dispose() {
    assert(_debugLifecycleState == _StateLifecycle.ready);
    assert(() {
      _debugLifecycleState = _StateLifecycle.defunct;
      return true;
    }());
  }
like image 52
hamamulfz Avatar answered Sep 21 '22 19:09

hamamulfz