casting int to bool in dart
Solution 1
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;
Solution 2
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
Solution 3
Try using a getter.
bool get status {
if(widget.studentDetailsList[index].status == 0)
return false;
return true;
}
Then pass status to value.
value: status
Comments
-
Jamshaid 5 daysI'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 parseinttoStringlike 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
inttoboolin dart. It saysConditions must have a static type of 'bool'.