What's the difference between "TextEditingController _controller;" and "final _controller = TextEditingController();"?

Viewed 33

I recently came across this doubt while declaring a controller for Textfield using TextEditingController _controller;. But it then resulted in an error as follows:

The following NoSuchMethodError was thrown while calling onChanged:
The getter 'text' was called on null.
Receiver: null
Tried calling: text

Then I randomly tried using final _controller = TextEditingController(); And to my surprise, it did work as expected.

I am quite familiar with the concepts of Object Oriented Programming (coming from a JAVA background). The thing that confuses me the most is why we don't need to initialise a variable declared with the other data types (for example, String s; works, and we don't need to declare and initilise it as var s = String();).

Also I might have framed the question wrongly and might be having completely wrong concepts regarding OOP.

1 Answers

The thing here is that when you've used TextEditingController _controller; you've only declared your variable and you didn't assign anything to it. It's like an empty box which you labeled it with TextEditingController! And when you tried to use it, compiler thrown an error indicating that it's null.

When you're using final _controller = TextEditingController(); you still have a TextEditingController box which compiler infers it's type by the value you've given to it. And since there is a value inside, you're not getting any errors. It's also possible to do something like this: final _controller; and it's totally fine. In this case you have a box (variable) with dynamic type and you can assign anything to it.

So your problem is not that you didn't define your first variable with final keyword. Your problem is that you didn't assign anything to the variable.

Related