如何编写返回字符串的内联函数?

时间:2019-02-20 09:45:02

标签: dart flutter

说我有一个傻函数返回一个字符串:

String oddMicrosecond() {
  if (DateTime.now().microsecondsSinceEpoch%2==0) {
    return "we're even";
  } else {
    return "that's odd";
  }
}

Text(oddMicrosecond());

是否可以将其作为匿名函数内联在Text声明中而无需单独定义?

1 个答案:

答案 0 :(得分:2)

您不需要为此功能

Text(DateTime.now().microsecondsSinceEpoch%2==0 ? "that's odd" : "we're even")

您可以

Text(() {
    if (DateTime.now().microsecondsSinceEpoch%2==0) {
      return "we're even";
    } else {
      return "that's odd";
    }
  }();
)