如果值为 null,则不执行赋值

发布于 2025-01-10 20:07:56 字数 1352 浏览 0 评论 0原文

我仍在了解 dart,并且想知道是否有一种更简单的方法可以在值为 null 时不执行语句。请参阅下面的示例:

我始终可以执行下面的 if 语句来设置 field3 和 field4,但感觉像 field5 这样的东西应该可以工作。但是当我尝试这样做时,它抱怨对 null 值使用了 null 检查运算符。

另外,我不想将地图更改为具有动态值。

是否有一个衬垫可以完成我想要做的事情,或者我只需要在设置值之前检查是否为空。

  Map<String, Object> myMap = {};

  print('running now');
  try {
    myMap['field1'] = DummyClass.getString('hello');
    myMap['field2'] = DummyClass.getString('good');

    //Is there a more concise way to do this than the 2 options below?

    if (DummyClass.getOptionalString('goodbye') != null) {
      myMap['field3'] = DummyClass.getOptionalString('goodbye')!;
    }

    String? temp = DummyClass.getOptionalString('go');
    if (temp != null) {
      myMap['field4'] = temp;
    }

    // This gives an error 'null check operator used on a null value'
    // myMap['field5'] ??= DummyClass.getOptionalString('to')!;

  } catch (e) {
    print('error condition, $e');
  }

  print(myMap);
}

class DummyClass {

  static String getString(String? strParam) {
    String? retString = getOptionalString(strParam);
    if (retString == null) {
      throw ('nulls are not allowed');
    }
    return retString;
  }

  static String? getOptionalString(String? strParam) {
    if (strParam == null || strParam.length < 3) {
      return null;
    }
    return strParam;
  }
}

I am still coming up to speed with dart and wanted to know if there was an easier way to not execute a statement if the value is null. See example below:

I can always do the if statements below for setting field3 and field4, but felt like something like field5 should work. But when I try to do that, it complains that a null check operator is used on a null value.

Also I don't want to change the Map to have a dynamic value.

Is there a single one liner to do what I am trying to do, or do I just need to check for null before setting the value.

  Map<String, Object> myMap = {};

  print('running now');
  try {
    myMap['field1'] = DummyClass.getString('hello');
    myMap['field2'] = DummyClass.getString('good');

    //Is there a more concise way to do this than the 2 options below?

    if (DummyClass.getOptionalString('goodbye') != null) {
      myMap['field3'] = DummyClass.getOptionalString('goodbye')!;
    }

    String? temp = DummyClass.getOptionalString('go');
    if (temp != null) {
      myMap['field4'] = temp;
    }

    // This gives an error 'null check operator used on a null value'
    // myMap['field5'] ??= DummyClass.getOptionalString('to')!;

  } catch (e) {
    print('error condition, $e');
  }

  print(myMap);
}

class DummyClass {

  static String getString(String? strParam) {
    String? retString = getOptionalString(strParam);
    if (retString == null) {
      throw ('nulls are not allowed');
    }
    return retString;
  }

  static String? getOptionalString(String? strParam) {
    if (strParam == null || strParam.length < 3) {
      return null;
    }
    return strParam;
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

嘴硬脾气大 2025-01-17 20:07:56

没有内置方法可以执行您想要的操作,但您可以编写一个函数(或扩展方法)来执行此操作。例如:

extension MapTrySet<K, V> on Map<K, V> {
  void trySet(K key, V? value) {
    if (value != null) {
      this[key] = value;
    }
  }
}

然后您可以这样做:

myMap.trySet('field3', DummyClass.getOptionalString('goodbye'));
myMap.trySet('field4', DummyClass.getOptionalString('go'));

或者,如果您确实想使用普通的 Map 语法,您可以创建自己的具有 void 运算符的 Map 类[]=(K key, V? value) 覆盖并且当 valuenull 时不执行任何操作,但这可能不值得付出努力。

There's no built-in way to do what you want, but you could write a function (or extension method) to do it. For example:

extension MapTrySet<K, V> on Map<K, V> {
  void trySet(K key, V? value) {
    if (value != null) {
      this[key] = value;
    }
  }
}

and then you could do:

myMap.trySet('field3', DummyClass.getOptionalString('goodbye'));
myMap.trySet('field4', DummyClass.getOptionalString('go'));

Alternatively, if you really want to use normal Map syntax, you could create your own Map class that has a void operator []=(K key, V? value) override and does nothing when the value is null, but that probably would not be worth the effort.

怎会甘心 2025-01-17 20:07:56

问题在于,如果 ??= 运算符为空,则它会分配给左侧。展开后,它看起来像这样:

a ??= b;

// Equivalent to:

if (a == null) {
  a = b;
}

这不是您想要实现的目标。 AFAIK,Dart 中还没有这样的运算符。不过,您可以尝试一下:

final possiblyNullValue = '';
final myMap = <String, String>{};

myMap['key'] = possiblyNullValue ?? myMap['key'];

// Equivalent to:

if (possiblyNullValue != null) {
  myMap['key'] = possiblyNullValue;
}

// or:

myMap['key'] = possiblyNullValue != null? possiblyNullValue : myMap['key'];

这对于您的情况来说可以作为一句台词。

The issue is that the ??= operator assigns to the left if it is null. Expanded, it would look something like this:

a ??= b;

// Equivalent to:

if (a == null) {
  a = b;
}

Which is not something that you're trying to achieve. AFAIK, there is no such operator yet in Dart. However, you can try this:

final possiblyNullValue = '';
final myMap = <String, String>{};

myMap['key'] = possiblyNullValue ?? myMap['key'];

// Equivalent to:

if (possiblyNullValue != null) {
  myMap['key'] = possiblyNullValue;
}

// or:

myMap['key'] = possiblyNullValue != null? possiblyNullValue : myMap['key'];

Which would work in your case as a one-liner.

错爱 2025-01-17 20:07:56

您可以使用所有条目(甚至为空)创建映射,然后过滤掉空值:

void main() {
  try {
    final myMap = <String, dynamic>{
      'field1': DummyClass.getString('hello'),
      'field2': DummyClass.getString('good'),
      'field3': DummyClass.getOptionalString('goodbye'),
      'field4': DummyClass.getOptionalString('go'),
    }..removeWhere((k, v) => v == null);
    print(myMap);
  } catch (e) {
    print('error condition, $e');
  }
}

You could create your map with all entries, even null, and then filter the null values out:

void main() {
  try {
    final myMap = <String, dynamic>{
      'field1': DummyClass.getString('hello'),
      'field2': DummyClass.getString('good'),
      'field3': DummyClass.getOptionalString('goodbye'),
      'field4': DummyClass.getOptionalString('go'),
    }..removeWhere((k, v) => v == null);
    print(myMap);
  } catch (e) {
    print('error condition, $e');
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文