Abhishek
Abhishek

Reputation: 63

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

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

Answers (3)

M Imam Pratama
M Imam Pratama

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

Lakshay
Lakshay

Reputation: 1

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

Upvotes: 0

nucleartux
nucleartux

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

Related Questions