6

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
     .
     .
     .
     )
    }
}
Abhishek
  • 63
  • 1
  • 1
  • 4

3 Answers3

9

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();
  }
}
nucleartux
  • 1,381
  • 1
  • 14
  • 36
  • Hey thanks for the solution! Just one more thing, is there a way through which I can maybe change updateNotesModel member's value even though flutter forces me to initialize it as final. Like widget.updateNotesModel.someValue = newValue? – Abhishek Mar 03 '19 at 19:31
  • It is ok. This variable shouldn't be const in parent widget. You can `setState` in a parent widget and then flutter rebuild widget tree and reinitialize your widget. – nucleartux Mar 03 '19 at 19:36
  • Or if you wont change it in this widget you should make `updateNotesModel` part of state, not widget. – nucleartux Mar 03 '19 at 19:37
  • Thanks again, I'll give it a try and hopefully I can figure it out! – Abhishek Mar 03 '19 at 19:46
2

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

M Imam Pratama
  • 998
  • 11
  • 26
0

that unfortunately cannot be done as, widget keyword cannot be accessed while initializing