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

时间:2020-02-17 00:34:52

标签: flutter dart

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

哪个是合适的?

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

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

3 个答案:

答案 0 :(得分:2)

抽象类状态:

  /// If you override this, make sure your method starts with a call to
  /// super.initState().
  @protected
  @mustCallSuper
  void initState() {
    assert(_debugLifecycleState == _StateLifecycle.created);
  }

答案 1 :(得分:2)

两者都可以。

但是,如果您发现任何依赖关系或官方文档出现问题,请在initSate()之后在super.initState();中编写代码

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

对此initState

的引用

dispose()相反,在super.dispose()之前编写代码。

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

dispose的引用

当我看到@Kahoo答案时,我通过cmd对其进行了检查,然后单击super.dispose和super.initstate,我发现这是要处理的

  /// 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;
    }());
  }

答案 2 :(得分:0)

两者都可以正常工作,但是更好的做法是在 protected void Upload(object sender, EventArgs e) { string filename = Path.GetFileName(FileUpload1.PostedFile.FileName); string contentType = FileUpload1.PostedFile.ContentType; using (Stream fs = FileUpload1.PostedFile.InputStream) { using (BinaryReader br = new BinaryReader(fs)) { byte[] bytes = br.ReadBytes((Int32)fs.Length); string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { string query = "insert into FileUploader2 values (@Name, @ContentType, @Data)"; using (SqlCommand cmd = new SqlCommand(query)) { cmd.Connection = con; cmd.Parameters.AddWithValue("@Name", filename); cmd.Parameters.AddWithValue("@ContentType", contentType); cmd.Parameters.AddWithValue("@Data", bytes); con.Open(); cmd.ExecuteNonQuery(); con.Close(); Context.Response.Write("Uploaded Successfully!"); } } } } Response.Redirect(Request.Url.AbsoluteUri); } 之前编写,因为它将在创建状态窗口小部件之前进行所有初始化,这将有助于您维护窗口小部件状态的检查。

但这并不意味着第二种方法不会对保持状态保持密切关注,但是从更好的实践来看,首选第一种方法。