Search code examples
flutterdartnullablenull-checkdart-null-safety

How to create null safe block in flutter?


How do I null check or create a null safe block in Flutter?

Here is an example:

class Dog {
  final List<String>? breeds;
  Dog(this.breeds);
}

void handleDog(Dog dog) {
    printBreeds(dog.breeds); //Error: The argument type 'List<String>?' can't be assigned to the parameter type 'List<String>'.
}

void printBreeds(List<String> breeds) {
  breeds.forEach((breed) {
    print(breed);
  });
}

If you try to surround it with an if case you get the same error:

void handleDog(Dog dog){
  if(dog.breeds != null) {
    printBreeds(dog.breeds); //Error: The argument type 'List<String>?' can't be assigned to the parameter type 'List<String>'.
  }
}

If you create a new property and then null check it it works, but it becomes bothersome to create new properties each time you want to null check:

void handleDog(Dog dog) {
  final List<String>? breeds = dog.breeds;
  if (breeds != null) {
    printBreeds(breeds); // OK!
  }
}

Is there a better way to do this?
Like the ?.let{} syntax in kotlin?


Solution

  • To get something similar to Kotlins .let{} i created the following generic extension :

    extension NullSafeBlock<T> on T? {
      void let(Function(T it) runnable) {
        final instance = this;
        if (instance != null) {
          runnable(instance);
        }
      }
    }
    

    And it can be used like this:

    void handleDog(Dog dog) {
      dog.breeds?.let((it) => printBreeds(it));
    }
    

    "it" inside the let function will never be null at runtime.

    Thanks to all the suggestions, but they were all some variation of moving the null check further down the code execution cain, which was not what i was looking for.