3

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.

Joe
  • 311
  • 3
  • 17

2 Answers2

4

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();
  }
EyaS
  • 477
  • 3
  • 9
  • 1
    Thanks! That was ist. I was redeclaring it by reusing TextEditingController in the declaration; I did not know that would have this effect. Thanks! Commenting helped a lot! – Joe Feb 21 '22 at 20:10
  • 1
    With `null safety` enabled you have to either declare the `textController` nullable by adding `?` or use `late`. Otherwise it won't work. – quoci Feb 21 '22 at 20:12
2

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();
      }

quoci
  • 2,940
  • 1
  • 9
  • 21