Dart: How Do I Use "optional Chaining" Or A Default Value?

- 1 answer

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?



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:

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.