'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?
Solution 1:[1]
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
Solution 2:[2]
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);
}
Solution 3:[3]
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.
Solution 4:[4]
Try with the following:
void mymethod(int? s) {
return s?.toString;
}
int? a = null;
mymethod(a);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sosnus |
Solution 2 | Dani3le_ |
Solution 3 | |
Solution 4 | lemon |