0

Sorry if this is a really simple question but still is a fundamental question for me to know what is the difference between these two line of code?:

TextEditingController titleController;

and

titleController = TextEditingController();

For more clearance I mean what would be the difference between titleController in the first line of the code versus the second line?

When we should use the first and when the second?


Bill Hileman
  • 2,798
  • 2
  • 17
  • 24

2 Answers2

1

Both lines must be used together. Let's see what each line represents:

The "first line":

TextEditingController titleController;

Is only declaring a variable of the TextEditingController type, called titleController. It has not been given a value yet, and while it doesn't receive one its value will be considered null.

There are other ways to declare a variable, (like declaring as dynamic, or using var, final, const, etc) and you can read more of that in the Dart's Language tour. I won't explain them here since it is not so much related to the question.

The "second line":

titleController = TextEditingController();

Is giving a value to the titleController declared variable. The value given is: TextEditingController(), which represents a new instance of a object from this class. You cannot do this line, without doing the other one first. Or else the compiler wouldn't know what the name titleController represents.

(Also, it makes sense, right? First you have a variable of a specific type, and you give this variable a value of that same type.)

So you usually do both. First you declare the variable, then you give it a value. Maybe because all of the keywords are related to "TextEditingController" it confuses a little bit. Here is an equivalent example with the String class:

String a; // the first line
a = "Your String"; // the second line

Which is equivalent and can be done in a single line as:

String a = "Your String";
// Or, in your case:
TextEditingController titleController = TextEditingController();

This way you both declare the variable and give it a initial value.

Naslausky
  • 3,443
  • 1
  • 14
  • 24
0

The first example is not initialized and the second example is. For me, there's no scenario where I would declare a TextEditingController without initializing it. Although you might be able to pass in a null controller into a TextFormField without an error, as soon as you try to do anything with it, like add a listener for example, you will get a "called on null" error.

You might as well just initialize it right off the bat, then it's ready to go immediately.

final titleController = TextEditingController();
Loren.A
  • 4,872
  • 1
  • 10
  • 17