简体   繁体   English

Dart:如何使用“可选链接”或默认值?

[英]Dart: How do I use "optional chaining" or a default value?

I'm coming from TypeScript to Dart because of Flutter and It's incredible how I can't do the simplest of things.因为 Flutter,我从 TypeScript 转向了 Dart,我不能做最简单的事情真是不可思议。

I have style?.p?我有style?.p? as double? double? and I would like to read its value or use 0.0 as a default.我想读取它的值或使用0.0作为默认值。 Like this:像这样:

EdgeInsets.all(style?.p != null ? style.p : 0.0))

... but Dart is saying double? ...但是 Dart 说的是double? can't be assigned to double .不能分配给double Well, I'm using this ternary expression to check for null , but I think Dart is not as smart as TypeScript in type inference.好吧,我正在使用这个三元表达式来检查null ,但我认为 Dart 在类型推断方面不如 TypeScript 聪明。

在此处输入图像描述

Any idea?任何想法?

试试这个,你可以给可选值,比如 (optionalVaribaleValue ?? DefaultValue) 所以如果 OptionalValue null 然后 DefaultValue 设置

EdgeInsets.all(style?.p ?? 0.0)

The reason why EdgeInsets.all(style?.p != null ? style.p : 0.0)) doesn't work is because only local variables can be type-promoted , and style.p is not a local variable. EdgeInsets.all(style?.p != null ? style.p : 0.0))不起作用的原因是只有局部变量可以进行类型提升,而style.p不是局部变量。 style.p therefore remains a double? style.p因此仍然是double? , causing the evaluated type of the conditional ternary expression to also be double? ,导致条件三元表达式的评估类型也是double? . .

Assigning style?.p to a local variable would work:style?.p分配给局部变量会起作用:

@override
void build(BuildContext context) {
  var p = style?.p;

  return ...
    padding: EdgeInsets.all(p != null ? p : 0));
}

but as others have noted (and as the Dart linter recommends ), you should prefer using a dedicated null operator:但正如其他人所指出的(并且正如Dart linter 所建议的那样),您应该更喜欢使用专用的 null 运算符:

padding: EdgeInsets.all(style?.p ?? 0);

where, because style?.p will not be evaluated multiple times (avoiding the potential for returning different values), ??在哪里,因为style?.p不会被多次评估(避免返回不同值的可能性), ?? can evaluate to a non-nullable type.可以评估为不可为空的类型。

Your style attribute is nullable plus the p property is nullable too, try doing this:您的 style 属性可以为空,并且 p 属性也可以为空,请尝试执行以下操作:

padding: style != null
            ? EdgeInsets.all(style!.p != null ? style!.p! : 0.0)
            : const EdgeInsets.all(0.0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM