I am creating a mileage tracking app that is based off of a tutorial for an expense tracker. I'm at the point that I am trying to create the function of _submitMileageData() with a check to make sure that at least a Title, Starting Mileage, and Date are selected. I don't care if the enteredEndingMiles is null or is 999999. Most of the time, it will most likely be null and will be entered at the end of the day and updated using an edit function.
The issue is, when I do the widget.onAddMileage portion, I get the red line under _endingMilesController.text. I've tried everything I can think of to convert it over to a double, but I can't seem to find the right combination of code to do it. I've even gone as far as trying to create a 'final endingMilesIsValid = enteredEndingMiles == null ...' and then start getting a boolean error. I try to rectify that by adding an else statement after my error check basically saying if the ending miles are null, just return. As long as it returns as a double at the end of the day so that the Total Miles can be calculated, that is all I care.
Enough of my rambling though... as I'm sure I probably didn't even explain this right with how fried my brain is... Here is the block of code I'm working in.
void _submitMileageData() {
final enteredStartingMiles = double.tryParse(_startingMilesController.text);
final startingMilesIsInvalid =
enteredStartingMiles == null || enteredStartingMiles <= 0;
if (_titleController.text.trim().isEmpty ||
startingMilesIsInvalid ||
_selectedDate == null) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('Invalid input.'),
content: Text(
'Please make sure a valid title, starting mileage, or date was entered.'),
actions: [
TextButton(
onPressed: () {
Navigator.pop(ctx);
},
child: Text('Ok'),
),
],
),
);
return;
}
widget.onAddMileage(
Mileage(
title: _titleController.text,
startMileage: enteredStartingMiles,
endMileage: _endingMilesController,
date: _selectedDate!,
category: _selectedCategory,
),
);
}
I appreciate any help or flaming that comes my way with this.
Thanks!
You get the error: "The argument type 'double?' can't be assigned to the parameter type 'double'." Because double.tryParse()
returns nullable double (double?
) "meaning it can be null if parsing fails"
And the parameter type is non-nullable double (double
) "meaning it always has a value and never can be null".
To fix this you have 2 options:
Choose a value to be used in case of null:
double x = double.tryParse('1.23') ?? 0.0;
Here the double x won't be null even if double.tryParse()
returns null the value 0.0 will be used.
Use null assertion operator (!)
since you checked if enteredStartingMiles == null
and handled that case, in the following lines of code you can say "trust me enteredStartingMiles is not null" by adding (!) at the end of variable name enteredStartingMiles!