How to access Stateful widget variable inside State class outside the build method?

半城伤御伤魂 提交于 2021-02-07 10:52:43

问题


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
     .
     .
     .
     )
    }
}

回答1:


You can do it in initState:

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

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


来源:https://stackoverflow.com/questions/54971210/how-to-access-stateful-widget-variable-inside-state-class-outside-the-build-meth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!