【问题标题】:How to loop through an array of variables in Dart如何在 Dart 中循环遍历变量数组
【发布时间】:2020-02-07 14:15:59
【问题描述】:
String A = null;
String B = null;
var C = List<someObject>();
...

不是检查编写代码来单独检查每个参数,而是想知道我们是否可以将所有这些参数放在一个数组中并循环检查是否不为空且不为空?谢谢

【问题讨论】:

  • 你绝对可以。如果值为 null 或为空,您想做什么?您的问题是StringList 没有公开isEmpty 的公共超类,因此您将不得不识别您关心的每种类型,或者在没有任何类型检查的情况下执行object.isEmpty 的乐观动态调用.

标签: dart


【解决方案1】:

这样的?

class SomeObject {}

void main() {
  String A = null;
  String B = null;
  var C = List<SomeObject>();

  if ([A, B, C].anyNull()) {
    throw "ARGHHHHH";
  }
}

extension AnyNullExtension on List {
  bool anyNull() => this.any((Object e) => e == null);
}

【讨论】:

    【解决方案2】:

    您可以像其他编程语言一样使用简单的 for 循环。

    for (var i=0; i<C.length; i++) {
       var notNull = C[i] ?? "someThingElse"
    }
    

    ?? 是 Dart 提供的 null 感知运算符之一

    【讨论】:

      【解决方案3】:

      这是一个示例代码:(您可以在 dartpad.dev 上查看)

      void main() {
        String A = null;
        String B = null;
        String D = "a real string";
        var C = List<String>();
        List<String> E = ["one", "two"];
      
        List items = [A, B, C, D, E];
      
        for(var i = 0; i < items.length; i++) {
          var item = items[i];
          var no = i + 1;
      
          if(item == null) {
            print("item " + no.toString() + " is null");
          }
          else if(item?.isEmpty ?? true) {
            print("item " + no.toString() + " is empty");
          }
      
          print("Item " + no.toString() + " is \"" + item.toString() + "\"");
        }
      }
      

      所以,首先您创建一个包含所有项目的列表。然后使用 for 循环(foreach 不适用于不同类型)检查每个项目。 要了解?。和??下面的结帐答案,在那里得到了很好的解释;) 除了打印,您还可以执行不同的操作,例如中断或抛出错误。

      也检查这个答案,它不会直接回答您的问题,但可能会避免它:)
      https://stackoverflow.com/a/17006968

      【讨论】:

        猜你喜欢
        • 2015-11-11
        • 2013-08-30
        • 2014-02-21
        • 1970-01-01
        • 2014-11-28
        • 1970-01-01
        • 2019-01-07
        • 2020-07-28
        相关资源
        最近更新 更多