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
Related
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;
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);
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 =[];
}
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.
I am trying to check value which I am receiving from the server, if a string is empty I am using the following condition.
var line2Cvar = permanentCAddVarDictionary?["line2"] as! String
if line2Cvar.isEmpty {
line2Cvar = "---"
}
self.permanentCAddDic.setValue(line2Cvar, forKey: "line2Cvar")
if a string is null I am using the following condition.
var line2Cvar = permanentCAddVarDictionary?["line2"]
if line2Cvar is NSNull {
line2Cvar = "----"
}
self.emergencyContactDic.setValue(line2Cvar, forKey: "line2Cvar")
but in my case sometimes I am getting empty and sometimes I am getting a null value. how check string is empty or null directly.
When checking for a string in a dictionary, you have 4 possible states:
the string is present, and non-empty
the string is present, but empty
the key is in the dictionary, but the value isn't a string
the key is absent from the dictionary
You have to check each case individually.
let possibleString = dict[key]
if let string = possibleString as? String {
if string.isEmpty {
// deal with empty case
} else {
// deal with non-empty case
}
} else if possibleString == nil {
// deal with key not-present case
} else {
// deal with value-not-string case
}
You can combine some checks and eliminate others, depending on the particular logic you require. For example, if you want to treat not-present and not-a-string the same way, you can eliminate the nil check, and just fall-through to the final else.
extension String {
var isEmptyNull:Bool {
let string = self.trimmingCharacters(in: CharacterSet.whitespaces)
if string == "" || string.lowercased() == "null" {
return true
}else {
return false
}
}
}
You can check here
let stringvalue = ""
if stringvalue.isEmptyNull {
print("string value is empty or null")
}else {
print(stringvalue)
}
output
string value is empty or null