Search code examples
flutterdartinstantiation

What is the difference between "TextEditingController titleController;" and "titleController = TextEditingController();"?


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?



Solution

  • 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.