flutterdartoperatorsdart-null-safetysyntactic-sugar

Syntactic sugar for calling a function with a nullable value that might return null


I am looking for syntactic sugar with null-safe-operators to do this:

map["key"] == null ? default : (int.tryParse(map["key"]!) ?? default)

This however accesses map twice and requires default twice. Better, but verbose code that also compiles:

String? val = map["key"];
int? res;
if (val != null) { res = int.tryParse(val) }
res ??= default;

In essence I am looking for a way to only call a function if the parameter is not null. E.g. in kotlin you could do (pseudocode)

map["key"].let{ int.tryParse(it) } ...

I found this related question, however writing helper methods is even more verbose and I cannot edit the function to take nullable parameters.

What i would love to see for dart (but afaik this does not exist):

int.tryParse(map["key"]?) ?? default;

I.e. func(null?) => null, no matter what func is, or sth similar.

Is there a smooth way to do that or is the verbose way for now the "accepted" way?

EDIT I am aware of the int.tryParse("") or int.tryparse(default.toString() hacks, however both are somewhat naughty as they will call tryParse either way instead of skipping it if the value is null anyways. (imagine replacing tryParse with a very expensive factory method)


Solution

  • There is two things you can do:

    int.parse(map["key"] ?? default.toString());
    

    This would work if you are sure that map["key"] can be parsed if it is not null. If you have to do this operation a lot you can also write your own extension function and then use the null-safe operator:

    extension NullSaveParser on String {
        int? tryToInt() {
            return int.tryParse(this);
        }
    }
    

    And then use this:

    map["key"]?.tryToInt() ?? default;
    

    This extension is neccessary because there is currently no way in dart to not call a method if an argument would be null, only if the object that you are calling it on is null can be caught. I hope this helps.