17
late TextEditingController _controller = TextEditingController();
late String someString = "someString";

TextEditingController _controller = TextEditingController();
String someString = "someString";

Are they still different? or exactly same??? on any circumstances (in performances)

dontknowhy
  • 2,480
  • 2
  • 23
  • 67

3 Answers3

12

The below statements

  1. late TextEditingController _controller = TextEditingController();
  2. TextEditingController _controller = TextEditingController();

Are both same?

It is just like saying var TextEditingController _controller = TextEditingController();

When to use late ?

In some instances you would not know the value of a variable initially. And the value could possibly be null.

As dart is null safe you have to either use ? or late keyword

var someString;  Flutter doesn't allow this

To overcome this you do either of the following:

   var someString?;  Saying flutter the value is nullable. So that flutter would warn you when you access this variable
   late someString;  You are assuring flutter that you will initialize this in your code before its used.

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
2

Declare variables that will be initialised later by using the late keyword.

late data_type variable_name;

When a late variable is used before it has been initialised, this error happens. You must keep in mind that although you used some variables or data that were marked as "late," their values were not altered or saved beforehand.

late String name;
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Text(name)
    //runtime error: 
    //LateInitializationError: Field 'name' has not been initialized.
  );
} 

This signifies that the variable name has no value at this time; it will be initialised in the Future. We have used this variable in the Text() widget without first initialising it.

To fix this problem

late String name;

@override
void initState() {
  name = "Flutter Campus";
  super.initState();
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Text(name)
  );
} 
1

Scenario 1

late TextEditingController _controller = TextEditingController();

Lazy Initialization:

when you add late before variable declaration then this will initialized when first it will be used.

Scenario 2

late String name;

use of late keyword to make variable non nullable and to initialize variable later so compiler will not give error of non-nullable instance field must be initialized. when we add late keyword we promise that we will initialize this variable before we use it.

Tariqali
  • 11
  • 2