Getting error parsing a value to an integer in flutter - flutter

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.

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);
}

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;

Related

Return value from if condition

I want to retrieve value from if statement of data not a null. At some point the data will be null so with my code it will return the initialize of string. How I want to retrieve the value from if condition that be null
String stringCheck() {
var checkStatus;
if (truckState.reported != null) {
var devStatus = truckState.reported?.data?.status;
checkStatus = devStatus;
return checkStatus;
}
return checkStatus;
}
I tried this somehow checkStatus still return null but I need data that hold inside if condition
In order to return nullable data, you need to change return data type to nullable String? stringCheck().
You can simply do
String? stringCheck() {
if (truckState.reported != null) {
String? devStatus = truckState.reported?.data?.status;
return devStatus;
}
}
Or just do
String? stringCheck()=>truckState.reported?.data?.status;
More about null-safety

Flutter Dart convert nullable int? to nullable String?

I must pass int? parameter to method where I can use only String? parameter. How to do it shorter?
void mymethod(String? s)
{
print(s ?? "Empty");
}
int? a = null;
mymethod(a == null ? null : a.toString()); // how do this line easier?
Edit: I can't change parameter mymethod(String? s) to mymethod(int? s) - it still must be String?
I don't know if I understood correctly, but you want this ?
void mymethod(String? s)
{
print(s ?? "Empty");
}
int? a; // this could be null already
mymethod(a?.toString()); // "a" could be null, so if it is null it will be set, otherwise it will be set to String
You could just do this:
mymethod(a?.toString());
But if you want to make the check, my suggestion is to make the function do it.
int? a;
mymethod(a);
void mymethod(int? s) {
String text = "Empty";
if (s != null) text = s.toString();
print(text);
}
literally shorter, "" with $can help, with more complex you need use ${} instead of $.
Example: mymethod(a == null ? null : "$a");
Or you can create an extensiton on Int? and just call extension function to transform to String?, short, easy and reuseable. you can write the extension code elsewhere and import it where you need it.
Try with the following:
void mymethod(int? s) {
return s?.toString;
}
int? a = null;
mymethod(a);

Flutter/Dart: Why does this statement effect null-nafety?

I realized this is just fine:
List<int> list = [];
int? b;
void addBarIfNull() {
if (b != null) {
list.add(b); // no problem
}
}
But adding this one statement b = null after adding b to the list, lets the linter complain with: The argument type 'int?' can't be assigned to the parameter type 'int':
List<int> list = [];
int? b;
void addBarIfNull() {
if (b != null) {
list.add(b); // problem: The argument type 'int?' can't be assigned to the parameter type 'int'
b = null;
}
}
Can someone explain what is going on here? Why is b considered as int? in list.add(b) if we clearly check before that it is not null? Why do both code snippets differ in handling this?
It is null safey issue when you declare
{
int? b;
}
you allow b to be null or have value but when you try to add
{
list.add(b);
}
b to the list you don't allow the list to contain null value that why the error message said you can't add int? to int you need to allow the list to contain null value if that whta you needed.
{
List<int?> list =[];
}

The return type 'int' isn't a 'String?', as required by the closure's context

what is the problem when I convert the string type value into an int so it will give me the following error mentioned in question.
If I understand your question correctly, you need to turn a String to int?
To do that, use int.parse(yourString) -> you will get int
If you are getting error with int and int? or String and String? (the same type but with question mark), try to use ?? operant
For example (with string value):
MyObject(
stringField: myString ?? '', //you are ensuring that if your String is null, there will be no error
);
if you want to return a String type data from int data, you need to convert it.
String test() {
int num = 0;
return(num.toString());
}
But if you want to return a int type data from String data, you need to parse it first to int.
int test() {
String pi = '3';
int now = int.parse(pi); // result from change String to int
return now;
}

casting int to bool in dart

I'm having a list of different types of values exported from JSON.
class StudentDetailsToMarkAttendance {
int att_on_off_status;
String name;
String reg_number;
int status;
StudentDetailsToMarkAttendance(
{this.att_on_off_status, this.name, this.reg_number, this.status});
factory StudentDetailsToMarkAttendance.fromJson(Map<String, dynamic> json) {
return StudentDetailsToMarkAttendance(
att_on_off_status: json['att_on_off_status'],
name: json['name'],
reg_number: json['reg_number'],
status: json['status'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['att_on_off_status'] = this.att_on_off_status;
data['name'] = this.name;
data['reg_number'] = this.reg_number;
data['status'] = this.status;
return data;
}
}
I am trying to use the value of status as the value parameter of Checkbox. I am trying to parse int to String like this.
value:((widget.studentDetailsList[index].status = (1 ? true : false) as int)as bool)
but there seems to be a problem with this conversion. I am not getting exact way of converting int to bool in dart. It says
Conditions must have a static type of 'bool'.
To convert int to bool in Dart, you can use ternary operator :
myInt == 0 ? false : true;
To convert bool to int in Dart, you can use ternary operator :
myBool ? 1 : 0;
There is no way to automatically "convert" an integer to a boolean.
Dart objects have a type, and converting them to a different type would mean changing which object they are, and that's something the language have chosen not to do for you.
The condition needs to be a boolean, and an integer is-not a boolean.
Dart has very few ways to do implicit conversion between things of different type. The only real example is converting a callable object to a function (by tearing off the call method), which is done implicitly if the context requires a function.
(Arguably an integer literal in a double context is "converted to double", but there is never an integer value there. It's parsed as a double.)
So, if you have an integer and want a bool, you need to write the conversion yourself.
Let's assume you want zero to be false and non-zero to be true. Then all you have to do is write myInteger != 0, or in this case:
value: widget.studentDetailsList[index].status != 0
Try using a getter.
bool get status {
if(widget.studentDetailsList[index].status == 0)
return false;
return true;
}
Then pass status to value.
value: status
I know this is an old question, but I think this is a clean way to convert from int to bool:
myBool = myInt.isOdd;
Or with null safety
myBool = myInt?.isOdd ?? false;
Try this:
value: widget.studentDetailsList[index].status == 1
I've just published a lib to convert any object to a bool value in dart, asbool (Disclaimer: I'm the author)
For int objects you can use it as a extension (.asBool) or helper method (asBool(obj)):
int? num = 23;
int? num2;
assert(num.asBool == true); // true == true
assert(asBool(num) == true); // true == true
assert(num2.asBool == false); // false == false
assert(0.asBool == asBool(null)); // false == false
assert(120.asBool == asBool(2.567)); // false == false
It also works for whatever other object like Strings, Iterables, Maps, etc.