( Error) The instance member widget can't be accessed in an initializer.Try replacing the reference to the instance member with a different expression

Viewed 39

In Flutter i am passing data to a new screen, Here is my first_Screen sending data

                        Navigator.push(
                        context,
                        MaterialPageRoute(
                              builder: (context) => updatenote(
                              id:      snapshot.data[index],
                              title:   snapshot.data[index]['title'],
                              content: snapshot.data[index]['content']),
                          ),
                        );

Here is my second screen getting data,

class updatenote extends StatefulWidget {
const updatenote({super.key, required this.id , required this.title , required this.content });
final dynamic id;
final dynamic title;
final dynamic content;

@override
State<updatenote> createState() => _updatenoteState();
}

class _updatenoteState extends State<updatenote> {

// instance of text_ediitng controllers 
final titleController   = TextEditingController(text: widget.title);
final contentController = TextEditingController(text: widget.content);

now the problem is i can't access widget.title and widget.content outside of my build , here i want to pass that data as a parameter to the TextEditingController. but get this (error)..

The instance member 'widget' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression

3 Answers

Can you try like this:

late final titleController;
late final contentController;
      @override
      void initState() {
        // instance of text_ediitng controllers 
        final titleController = TextEditingController(text: widget.title);
        final contentController = TextEditingController(text: 
        widget.content);
        super.initState();
      }

You could define them as late

late final titleController = TextEditingController(text: widget.title);
late final contentController = TextEditingController(text: widget.content);

This makes it that the assignment happens lazily, meaning it happens at the point where you first use them. This allows it to use widget there

try this

class updatenote extends StatefulWidget {
  final titleController   = TextEditingController();
  final contentController = TextEditingController();
  final dynamic id;
  final dynamic title;
  final dynamic content;
  const updatenote({super.key, required this.id , required this.title , required this.content }) {
    titleController.text = title;
    contentController.text = content;
  }

  @override
  State<updatenote> createState() => _updatenoteState();
}
Related