如何在build方法之外的State类中访问有状态的小部件变量? [英] How to access Stateful widget variable inside State class outside the build method?

查看:76
本文介绍了如何在build方法之外的State类中访问有状态的小部件变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问_UpdateNotesState中的代码中声明的'updateNotesModel'变量.我发现您可以使用"widget"关键字来做到这一点,如下面的脚手架所示.但是这里的问题是,我试图在build方法之外访问变量,以便为TextEditingController提供默认值.我该如何实现?

I am trying to access the 'updateNotesModel' variable declared in the code in the _UpdateNotesState. I found out that you can do it using the 'widget' keyword as shown in the Scaffold below. But the problem here is that I am trying to access the variable outside the build method in order to give the TextEditingController a default value. How can I achieve this?

class UpdateNotes extends StatefulWidget {

  final NotesModel updateNotesModel;
  UpdateNotes({Key key, this.updateNotesModel}): super(key: key);

  @override
  _UpdateNotesState createState() => _UpdateNotesState();
}

class _UpdateNotesState extends State<UpdateNotes> {

  TextEditingController _titleController = 
new TextEditingController(text: widget.updateNotesModel.someValue); //getting an error
}

@override
  Widget build(BuildContext context) {
    return Scaffold(
    var a = widget.updateNotesModel.someValue
     .
     .
     .
     )
    }
}

推荐答案

您可以在 initState 中进行操作:

class _UpdateNotesState extends State<UpdateNotes> {
  TextEditingController _titleController = new TextEditingController(); 

  @override
  void initState() {
    _titleController.text= widget.updateNotesModel.someValue;
    super.initState();
  }
}

这篇关于如何在build方法之外的State类中访问有状态的小部件变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆