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;
CodePudding user response:
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.
CodePudding user response:
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?
CodePudding user response:
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.