Reputation: 63
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
.
.
.
)
}
}
Upvotes: 6
Views: 10937
Reputation: 1279
Now you can use the late
keyword. From the docs:
Dart 2.12 added the
late
modifier, which has two use cases:
- Declaring a non-nullable variable that’s initialized after its declaration.
- Lazily initializing a variable.
class _UpdateNotesState extends State<UpdateNotes> {
late TextEditingController _titleController = new TextEditingController(text: widget.updateNotesModel.someValue);
@override
Widget build(BuildContext context) {
.
.
.
}
}
Upvotes: 2
Reputation: 1
that unfortunately cannot be done as, widget keyword cannot be accessed while initializing
Upvotes: 0
Reputation: 1390
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();
}
}
Upvotes: 9