Home > Mobile >  The instance member 'firstName' can't be accessed in an initializer
The instance member 'firstName' can't be accessed in an initializer

Time:03-27

I'm trying to give default value to a TextFormField using text: parameter in it's controller

class _EditProfileState extends State<EditProfile> {

  String firstName = "Sushant";

  TextEditingController firstNameController = TextEditingController(text: firstName);

But am getting the following error

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

CodePudding user response:

Here you are trying to initiate firstNameController with a non-constant value. firstName here is not static and belongs to the instance. When the class is created, it cannot access properties of itself because they are not created either (nothing guarantees that firstName is created before firstNameController).

However, you can use the late keyword:

class _EditProfileState extends State<EditProfile> {

  String firstName = "Sushant";

  late TextEditingController firstNameController = TextEditingController(text: firstName);
}

late will make firstNameController "lazy". It means it is only going to be evaluated when called (and not when your class instance is created). Therefore, when using the late keyword, when evaluated, your class is already created with its properties and you can access them.

CodePudding user response:

Since you are using State, set default text in initState.

This will only trigger once when Widget is initialized. Also set all TextEditingController as final, you should not assign new one later.

Last, remember to dispose it.

String firstName = "Sushant";
final TextEditingController firstNameController = TextEditingController();

@override
void initState() {
  firstNameController.text = firstName;
  super.initState();
}

@override
void dispose() {
  firstNameController.dispose();
  super.dispose();
}

CodePudding user response:

Try to use late with TextEditingController then initialize TextEditingController inside initState.

class _EditProfileState extends State<EditProfile> {

  String firstName = "Sushant";
  late TextEditingController firstNameController;

  @override
  void initState() {
    firstNameController = TextEditingController(text: firstName);
  }
}

@override
void dispose() {
  firstNameController.dispose();
  super.dispose();
}

Or use

class _EditProfileState extends State<EditProfile> {
        
    String firstName = "Sushant";
    TextEditingController firstNameController = TextEditingController();
        
    @override
    void initState() {
       firstNameController.text = firstName;
    }
}

@override
void dispose() {
   firstNameController.dispose();
   super.dispose();
}
  • Related