Why are the variables in initState not acessible?

Issue

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.

Solution

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

Answered By – EyaS

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *