Home > Net >  Flutter Dart convert nullable int? to nullable String?
Flutter Dart convert nullable int? to nullable String?

Time:05-13

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?

CodePudding user response:

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

enter image description here

CodePudding user response:

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

CodePudding user response:

just like this:
void mymethod(int? s) {
  return s?.toString;
}
int? a = null;
mymethod(a);

CodePudding user response:

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.

enter image description here

  • Related