Flutter Dart 转换可为空的 int?可以为空的字符串?

Flutter Dart convert nullable int? to nullable String?

我必须将 int? 参数传递给只能使用 String? 参数的方法。如何缩短?

void mymethod(String? s)
{
   print(s ?? "Empty");
}
int? a = null;
mymethod(a == null ? null : a.toString()); // how do this line easier?

编辑:我无法将参数 mymethod(String? s) 更改为 mymethod(int? s) - 它仍然必须是 String?

字面上更短,""$ 可以提供帮助,如果更复杂,您需要使用 ${} 而不是 $

示例mymethod(a == null ? null : "$a");

或者您可以在 Int? 上创建一个扩展,只需调用扩展函数即可转换为 String?,简短、简单且可重用。您可以在其他地方编写扩展代码并在需要的地方导入它。

不知道我理解的对不对,你要这个?

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

你可以这样做:

mymethod(a?.toString());

但是如果你想做检查,我的建议是让函数来做。

int? a;
mymethod(a);

void mymethod(int? s) {
   String text = "Empty";
   if (s != null) text = s.toString();
   print(text);
}

尝试以下方法:

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