I am having this code below
int? _trades = data['trades'] ?? 0;
so I want to parse data['trades'] to an integer so I did this
int? _trades = int.parse(data['trades']) ?? 0;
But I got this error:
The left operand can't be null, so the right operand is never executed. Try removing the operator and the right operand.
CodePudding user response:
Generally we use ??
in dart when we expect a null
value from source and we want to assign a fallback value.
But as mentioned by @omkar76 int.parse()
does not return the null hence there is no point using ?? 0
at the end because it will never return null instead it will just throw an error.
In order to catch the error you can place try/catch around the int.parse()
that way you'll be safely parse the code and your error will get disappear.
Example code
void main() {
var data = {'trades': '2'};//sample data
int trades = 0; //setting default value
try {
int trades = int.parse(data['trades']!);
} catch (e) {
print('[Catch] $e');
}
print(trades);
}
CodePudding user response:
int? _trades = data['trades'] ?? 0;
Int? Means the value can be null but you also added ?? Which means if its null then assign 0.
So you can either use
int? _trades = data['trades'];
//Or
int _trades = data['trades'] ?? 0;