Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter, late keyword with declaration

Tags:

flutter

dart

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)

like image 324
dontknowhy Avatar asked Nov 22 '25 13:11

dontknowhy


2 Answers

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.

like image 146
krishnaacharyaa Avatar answered Nov 25 '25 09:11

krishnaacharyaa


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)
  );
} 
like image 23
Mani Baluchamy Avatar answered Nov 25 '25 10:11

Mani Baluchamy