代码应该写在 super.initState() 之前吗?还是在 Flutter 之后?

kam*_*vyz 8 dart flutter

编写initState()函数的代码应该写在之前super.initState();还是之后?

哪一个合适:

  @override
    // code here
    super.initState();
  }
Run Code Online (Sandbox Code Playgroud)

或者

  @override
    super.initState();
    // code here
  }
Run Code Online (Sandbox Code Playgroud)

ham*_*lfz 11

两者都会起作用。

但是,如果您从任何依赖项或官方文档中看到颤动,请在initSate()后面编写您的代码super.initState();

@overrride
initState(){
  super.initState()
  //your code
}
Run Code Online (Sandbox Code Playgroud)

引用此initState

与此相反dispose(),在 super.dispose() 之前编写代码;

@overrride
dispose(){
  //your code
  super.dispose()
}
Run Code Online (Sandbox Code Playgroud)

参考处置

当我看到 @Kahoo 答案时,我通过 cmd + 单击 super.dispose 和 super.initstate 进行检查,我发现这是用于 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;
    }());
  }
Run Code Online (Sandbox Code Playgroud)