这些符号是什么意思??=在颤动中
What do these symbols mean ??= in flutter
我在某些 class 中发现了这一点,但不确定它们的作用
??
, ??=
示例:
cursorColor ??= selectionTheme.cursorColor ?? cupertinoTheme.primaryColor;
??
用于为 null 情况提供默认值。
int? a ;
int b = a?? 0;// it a is null b will get 0
b ??= value;
Assign value to b if b is null; otherwise, b stays the same
cursorColor ??= selectionTheme.cursorColor ?? cupertinoTheme.primaryColor;
如果cursorColor
值为空,则使用右边的部分。
如果它发现 selectionTheme.cursorColor
等于 null,那么它将 return cupertinoTheme.primaryColor
.
这些是 Null-aware 个运算符。
假设我们有一个 int
,并在此基础上完成我们的示例,如下所示:
int? item; // this one is currently null, since there's no value defined as default.
item ??= 10; // here we check if `item` is null define new value for `item`.
print(item); // and here, base on above codes, we should get 10 because in above code
// we've checked our `item` if it's not null, define a new value.
现在基于上面的例子,我们可以做:
item ??=5; // in this case, since item is not null, and we've a value for `item`
// already, we should get 10.
print(item); // 10 will be print since in second operator checked null value for variable
// and in this case value wasn't null this time.
在这种情况下,另一个 ??
将在运算符左侧的 return 值,以防运算符左侧不为空,例如:
print(10 ?? 15); // this will return 10, because left side of operator isn't null.
print(null ?? 20); // this one will return 20, because left side of operator is null.
所以根据你的代码,如果我们将你的代码分成两部分,你的代码会检查 cursorColor
是否为 null,它将尝试 return 基于第二部分的新值您的代码,在那部分,它将检查另一个空值。
我在某些 class 中发现了这一点,但不确定它们的作用
??
, ??=
示例:
cursorColor ??= selectionTheme.cursorColor ?? cupertinoTheme.primaryColor;
??
用于为 null 情况提供默认值。
int? a ;
int b = a?? 0;// it a is null b will get 0
b ??= value;
Assign value to b if b is null; otherwise, b stays the same
cursorColor ??= selectionTheme.cursorColor ?? cupertinoTheme.primaryColor;
如果cursorColor
值为空,则使用右边的部分。
如果它发现 selectionTheme.cursorColor
等于 null,那么它将 return cupertinoTheme.primaryColor
.
这些是 Null-aware 个运算符。
假设我们有一个 int
,并在此基础上完成我们的示例,如下所示:
int? item; // this one is currently null, since there's no value defined as default.
item ??= 10; // here we check if `item` is null define new value for `item`.
print(item); // and here, base on above codes, we should get 10 because in above code
// we've checked our `item` if it's not null, define a new value.
现在基于上面的例子,我们可以做:
item ??=5; // in this case, since item is not null, and we've a value for `item`
// already, we should get 10.
print(item); // 10 will be print since in second operator checked null value for variable
// and in this case value wasn't null this time.
在这种情况下,另一个 ??
将在运算符左侧的 return 值,以防运算符左侧不为空,例如:
print(10 ?? 15); // this will return 10, because left side of operator isn't null.
print(null ?? 20); // this one will return 20, because left side of operator is null.
所以根据你的代码,如果我们将你的代码分成两部分,你的代码会检查 cursorColor
是否为 null,它将尝试 return 基于第二部分的新值您的代码,在那部分,它将检查另一个空值。