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)
The below statements
late TextEditingController _controller = TextEditingController();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.
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)
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With