Skip to content

Provide an expression to maybe provide an optional parameter #1401

@Wikiwix

Description

@Wikiwix

As discussed on Discord there is no short solution to apply an optional parameter maybe a value using an expression:

//@dart=2.12
class Sample {
  const Sample({this.a = 42});
  final int a;
}

Sample someFunction() {
  int? value;
  // ...
  // calculations do potentially set value
  // ...

  // **The following line is not valid in Dart >= 2.12**,
  // but the *expected / hoped for* output would be
  // `value != null ? Sample(a: value) : Sample()`
  return Sample(a: value);

  // # Work-arounds I see currently

  return Sample(a: value ?? 42);
  // Means you hardcode a default that might change over time

  return value != null ? Sample(a: value) : Sample();
  // In this sample okayish, but imagine `Sample` was a `Widget`
  // where you set ~10 named parameters, each potentially being an expression again

 
  // # Something I thought might potentially work, but does not 🙊
  // I guess this is very wrong from a grammar/semantics PoV
  return Sample(a: value ?? Never);
}

The same issue should apply for optional positional parameters.

Did not have the time yet to fully read on the Pattern language feature draft, but I can imagine that there might be some ”connection“ in the long run.

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions