Create nullable object based on nullable value


i have to create a domain class object which has a nullable attribute. This Creating is in an extansion of a primitive class.

For example: Domainclass

Meeting({required String id, required Datetime date, Example? example})

behind Example is an class like so: Example(String value)


extension MeetingPrimitiveX on Meeting {

Meeting toDomain() {
  return Meeting(
    id: id,
    date: date,
    example: example == null ? null : Example(example)


My question is, how can i simplify this:

example == null ? null : Example(example)

thanks in advance


You generally can’t.
You can change it in various ways, but nothing is more direct than what you have here.

One variant would be:

extension DoWith<T> on T {
  R doWith<R>(R Function(T) action) => action(this);

With that, you can write:


to conditionally call the constructor (tear-off of the unnamed constructor) if example is non-null.

Slightly shorter, requires a helper function, and … isn’t actually more readable IMO.

Answered By – lrn

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *