问题
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