什么是 ?? Dart中有两个问号?

时间:2019-01-04 00:48:58

标签: dart operators

下面的代码行带有两个问号:

final myStringList = prefs.getStringList('my_string_list_key') ?? [];

什么意思?

3 个答案:

答案 0 :(得分:27)

??双问号运算符的意思是“如果为空”。以下面的表达式为例。

String a = b ?? 'hello';

这意味着a等于b,但是如果b为空,则a等于'hello'

另一个相关的运算符是??=。例如:

b ??= 'hello';

这意味着如果b为空,则将其设置为hello。否则,请勿更改。

参考

条款

Dart 1.12 release news统称为空感知运算符

  • ??-如果为空运算符
  • ??=-可以识别空值的
  • x?.p-可以识别空值的访问
  • x?.m()-空值方法调用

答案 1 :(得分:8)

Dart 提供了一些方便的运算符来处理可能为 null 的值。一个是 ??= 赋值运算符,它仅在变量当前为 null 时才为该变量赋值:

int a; // The initial value of a is null.
a ??= 3;
print(a); // <-- Prints 3.

a ??= 5;
print(a); // <-- Still prints 3.

另一个空感知运算符是??,它返回左边的表达式,除非该表达式的值为空,在这种情况下,它会计算并返回右边的表达式:

print(1 ?? 3); // <-- Prints 1.
print(null ?? 12); // <-- Prints 12.

答案 2 :(得分:0)

这在 copyWith 方法中特别有用,该方法在 flutter 中经常用于覆盖。 下面是一个例子:

import './color.dart';
import './colors.dart';

class CoreState {
  final int counter;
  final Color backgroundColor;

  const CoreState({
    this.counter = 0,
    this.backgroundColor = Colors.white,
  });

  CoreState copyWith({
    int? counter,
    Color? backgroundColor,
  }) =>
      CoreState(
        counter: counter ?? this.counter,
        backgroundColor: backgroundColor ?? this.backgroundColor,
      );

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is CoreState &&
              runtimeType == other.runtimeType &&
              counter == other.counter &&
              backgroundColor == other.backgroundColor;

  @override
  int get hashCode => counter.hashCode ^ backgroundColor.hashCode;


  @override
  String toString() {
    return "counter: $counter\n"
            "color:$backgroundColor";
  }
}
相关问题