Home > database >  Dart: How do I use "optional chaining" or a default value?
Dart: How do I use "optional chaining" or a default value?

Time:02-21

I'm coming from TypeScript to Dart because of Flutter and It's incredible how I can't do the simplest of things.

I have style?.p? as double? and I would like to read its value or use 0.0 as a default. Like this:

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

... but Dart is saying double? can't be assigned to 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.

enter image description here

Any idea?

CodePudding user response:

try this you can give the optional value like (optionalVaribaleValue ?? DefaultValue) so if OptionalValue null then DefaultValue set

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

CodePudding user response:

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. style.p therefore remains a double?, causing the evaluated type of the conditional ternary expression to also be double?.

Assigning style?.p to a local variable would work:

@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:

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

where, because style?.p will not be evaluated multiple times (avoiding the potential for returning different values), ?? can evaluate to a non-nullable type.

CodePudding user response:

Your style attribute is nullable plus the p property is nullable too, try doing this:

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