Home > Software design >  Why are the variables in initState not acessible?
Why are the variables in initState not acessible?

Time:02-22

I want to create a TextController in the initState and then dispose of it like a good boy in dispose. But for some reason, the controller is not avaiable outside of the intiState:

class _InputFieldEnterThingState extends State<InputFieldEnterThing> {
  @override
  void initState() {

    TextEditingController textController =
        TextEditingController(text: 'placeholder');
    super.initState();
  }

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

It tells me "textController" is not defined in dispose() ... same, if I try using it in the build method. It's, as if the varialbe is strictly local in initState. I feel I'm missing something super obvious, but cannot find it.

CodePudding user response:

The textController is a local variable in the initState method, you need to make him global and the dispose method will recognize him.

The way to do that:

class _InputFieldEnterThingState extends State<InputFieldEnterThing> {
  TextEditingController textController;  // make him global


  @override
  void initState() {
    textController =  // without redefine
        TextEditingController(text: 'placeholder'); 
    super.initState();
  }

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

CodePudding user response:

Since you declared the variable textController inside initState the variable is only accessible in initState. If you want to access textController e.g. in dispose, you have to declare it outside the initState.

class _InputFieldEnterThingState extends State<InputFieldEnterThing> {
      late TextEditingController textController;
     
      @override
      void initState() {
        textController = TextEditingController(text: 'placeholder');
        super.initState();
      }
    
      @override
      void dispose() {
        textController.dispose();
        super.dispose();
      }

  • Related