字符串中的颤振三元运算符不起作用

时间:2021-02-26 23:45:35

标签: flutter dart

我使用三元运算符来避免文本小部件中的空值。

如果变量为空,我会假设 noData 作为值。但是在调试的时候我发现三元运算符直接跳了出来,没有去ELSE。

如果变量不为空,它工作正常。

    String noData = "No data available";

.....

                  Text(
                    "Population:",
                    style: TextStyle(
                      fontSize: 18.0,
                      fontWeight: FontWeight.values[4],
                    ),
                  ),
                  Text(
                    "${country.data.last.population != null ? country.data.last.population : noData}",
                    style: TextStyle(
                      fontSize: 16.0,
                    ),
                  ),

.....

2 个答案:

答案 0 :(得分:0)

您忘记了默认字符串 'noData' 周围的引号。

您可能想做:

Text('${country.data.last.population != null ? country.data.last.population : 'noData'}'),

但为什么不更简单:

Text(country.data.last.population ?? 'noData'),

回答以下评论的简单示例:

void main() {
  String noData = "No data available";
  double value;
  print("${value != null ? value : noData}");     // No data available
  print("${value ?? noData}");                    // No data available
  value = 10.0;
  print("${value != null ? value : noData}");     // 10
  print("${value ?? noData}");                    // 10
}

答案 1 :(得分:0)

您的数据存在问题导致该错误。这不是 Dart 语言的问题。您可以在我所在的 https://dartpad.dev/ 上尝试以下示例,就像您一样,从对象内部获取 String 值并检查它是否为空。它适用于两种情况:

void main() {
  Person person1 = Person(name: 'John', age: 35);
  Person person2 = Person(age: 22);
  
  print("${person1.name != null ? person1.name : 'no name'}");
  print("${person2.name != null ? person2.name : 'no name'}");
}

class Person {
  String name;
  int age;
  
  Person({
    this.name,
    this.age
  });
}

控制台

约翰

没有名字