Im using some code from a tutorial but putting it in my own app. I cant figure out the next warning and how to solve:
LateInitializationError: Field ‘_durationRemaining#585382383’ has not been initialized.
The code(piece of the whole code) where this error is from is:
late MapBoxNavigation _directions;
late MapBoxOptions _options;
bool _isMultipleStop = false;
late double _distanceRemaining, _durationRemaining;
late MapBoxNavigationViewController _controller;
bool _routeBuilt = false;
bool _isNavigating = false;
#override
void initState() {
super.initState();
initialize();
}
The error is about the rule:
late double _distanceRemaining, _durationRemaining;
Am i doing something wrong? Maybe because i have 2 fields behind the late double and not the right way?
If i delete the Late in front of double, then get this errors:
lib/main.dart:42:10: Error: Field ‘_distanceRemaining’ should be initialized because its type ‘double’ doesn’t allow null.
double _distanceRemaining, _durationRemaining;
^^^^^^^^^^^^^^^^^^
lib/main.dart:42:30: Error: Field ‘_durationRemaining’ should be initialized because its type ‘double’ doesn’t allow null.
double _distanceRemaining, _durationRemaining;
When defining any variable as late, it must be initialized with the specified type before accessing it. In your case, it should be initialized in the initState() function. If you don't want to use the late keyword, you could make your variable nullable by using the ? operator.
For Eg
double? _distanceRemaining, _durationRemaining;
This would make your double variable nullable meaning it could accept null values.
If I do that I get:
264:60: Error: Operator '/' cannot be called on 'double?' because it is potentially null.
? "${(_durationRemaining / 60).toStringAsFixed(0)} minutes"
272:60: Error: Operator '*' cannot be called on 'double?' because it is potentially null.
? "${(_distanceRemaining * 0.000621371).toStringAsFixed(1)} miles"
The code there is:
? "${(_durationRemaining / 60).toStringAsFixed(0)} minutes"
? "${(_distanceRemaining * 0.000621371).toStringAsFixed(1)} miles"
I have to change something there also I guess. Because there it cant be null?
When a variable is nullable, you are restricted to using the normal operations and function calls that can be used on non-nullable variables.
For eg
double? _durationRemaining;
var x = _durationRemaing + 10;
You cannot do this operation because _durationRemaing can be null. For this, you can use the ?? operator, which checks whether the variable is null or not.
var x = (_durationRemaing ?? 0) + 10;
This means that if the variable is null use 0 as the value. So you have to use the ?? operator in your code mentioned above.
Related
Before null-safety, we know that if we declare variable like this
int a;
Then a is pointing to a null object.
But, now with sound null safety, when we declare the non-nullable variable with late keyword like this,
late int b;
Then, what is the value in b ? or in other words, b is pointing to what ?
The late keyword means that you are going to define new value as soon as possible, but you definitely will, so if you won't set any value to and use it, it will through an exception like this:
LateInitializationError: Field 'b' has not been initialized.
So it does not mean that b is null when you use it, it means that although it is null now it will get value very soon before you use b.
please check here
late keyword is used initialise soon. so you need check that data is null or not. if it's null means you should initialise or assign
late int N;
print(N ?? 123); // checking N is null if it null means by default assign the 123.
I was trying to create a class for questions so that I can use it in main.dart file in my Quiz App but I encountered some errors. Please tell me Why these errors came and How can I resolve them?
class Question:
class Question {
String questionText;
bool questionAnswer;
Question({String q, bool a}) {
questionText = q;
questionAnswer = a;
}
}
Errors:
Non-nullable instance field 'questionAnswer' must be initialized.
Non-nullable instance field 'questionText' must be initialized.
The parameter 'q' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
The parameter 'a' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Image of Errors here.
The issue is about null-safey, you need to make fields nullable, late or add required on constructor.
class Question {
late String questionText;
late bool questionAnswer;
Question({required String q, required bool a}) {
questionText = q;
questionAnswer = a;
}
}
class Question {
String questionText;
bool questionAnswer;
Question({required this.questionAnswer, required this.questionText});
}
Find more about -null-safety
Yeasin's answer is probably what you want, but I want to expand on null safety.
so dart, the underlying language, now has something called "null safety".
This means that unless you tell dart the variable can be null, it will complain when a non-nullable variable is not given a variable.
Example
class Question{
String complaint; // complain because it is not initialised
String fine = ""; // no complaint, because we have a string variable, though it is empty.
late String lateString; // tells the compiler don't worry. I'll define it later in the constructor while the object in being created
String nullable?; // tells the compiler this variable can be null
}
using variables that can be null comes with a host of other things to think about. so I advise looking into it. I've linked a really easy video on the topic (depending on your skill you might be okay to find a faster video)
https://www.youtube.com/watch?v=llM3tcpaD5k
Error: Uncaught LateInitializationError: Field 'deviceToken' has not been initialized.
Not sure what went wrong here.
late String deviceToken;
var registerRepo = GoogleSignInRepo();
FirebaseAuth auth = FirebaseAuth.instance;
Future<String> gettoken() async {
final String? token = await FirebaseMessaging.instance.getToken();
return token!;
}
#override
void initState() {
gettoken().then((value) {
deviceToken = value;
});
super.initState();
}
Well the error pretty much tells you the problem:
Error: Uncaught LateInitializationError: Field 'deviceToken' has not been initialized.
Flutter is null-safe, therefore if you define a variable you need to assign a value to it since the value by definition is not allowed to be null. Keep in mind that the late keyword only tells you that the variable will be initialized at runtime instead of compile time.
This means that some other part of your code probably accesses deviceToken before it was initialized in your Future.
You can solve it like this:
// Assign a value (empty string in this case).
String deviceToken = "";
Another solution would be to make your field nullable and this is probably the better solution in your case.
// Null is a valid value and will not cause a error.
String? deviceToken;
Or: Make sure the field was initialized before you access it.
For further reference this article might help you out:
https://dart.dev/null-safety/understanding-null-safety
I have made a BMI calculator in flutter. I am new in flutter. After running the code i am receiving the above warning. Kindly provide me the solution of this problem. Below attached is the link of the code
Link of the dart file
You are declaring the _result variable as non-nullable,
late double _result;
However you do a null check
null == _result ? "Enter Value" : _result.toStringAsFixed(2),
So change your variable declaration to this,
double? _result;
And then you can null check this way
_result?.toStringAsFixed(2) ?? "Enter Value" ,
You declared the result variable like this:
late double _result;
_result is the name of the variable, double is the type.
late means you are not yet assigning a value to it.
A late variable is different from a nullable variable in the sense that a nullable variable's value could be null, a late variable doesn't have a value until you assign one.
late int xd;
if (xd == null) {
}
the above if will always be false because xd's value is not null, xd has no value at all.
a nullable variable is determined with a ? after the type:
double? _result;
which means that if you haven't assigned anything to it, it will be null, but you can also assign null directly.
_result = null;
the above is not possible for a late variable.
Try changing the extractedData to jsonDecode(response.body)
from
if (extractedData == null)
to
if (jsonDecode(response.body) == null)
I think in new Dart rules the variables can not be declared/initialized as null. So we must put a late keyword before the variable type like below:
late String id;
Or a ? mark after the variable type like below:
String? id;
Are these two equal Or there are some differences?
A nullable variable does not need to be initialized before it can be used.
It is initialized as null by default:
void main() {
String? word;
print(word); // prints null
}
The keyword late can be used to mark variables that will be initialized later, i.e. not when they are declared but when they are accessed. This also means that we can have non-nullable instance fields that are initialized later:
class ExampleState extends State {
late final String word; // non-nullable
#override
void initState() {
super.initState();
// print(word) here would throw a runtime error
word = 'Hello';
}
}
Accessing a word before it is initialized will throw a runtime error.
when you use late keyword you can't let variable uninitialized when you called it with ? allows to you let variable uninitialized when you create it and call it
Null safety rules doesn't mean you can't use null. You can, but you should indicate that a variable might have the value null, by add "?" to its type declaration.
By use keyword late you indicate that variable has a non-nullable type, is not initialized yet, but will be initialized later.
Exception is thrown if try to acсess value of late variable before initialization.