How to solve: A value of type 'xxx?' can't be returned from a function with return type 'xxx' because 'xxx?' is nullable and 'xxx' isn't

Question

Asked by zarkli on January 11, 2022 (source).

I am learning factory method in dart. However I encounter a problem, which says

A value of type 'Person?' can't be returned from a function with return type 'Person' because 'Person?' is nullable and 'Person' isn't. 3-1.dart:13

Here is my code:

void main(List<String> args) {
  Person a = new Person("zarkli");
  a.say("hello");
}

class Person{
  final name;
  static final Map<String, Person> _cache = new Map<String,Person>();

  factory Person(String name){
    if (_cache.containsKey(name)){
      return _cache[name]; // error
    } else {
      final person = new Person.newPerson(name);
      _cache[name] = person;
      return person;
    }
  }
  Person.newPerson(this.name);
  
  void say(String content){
    print("$name: $content");
  }
}

Answer

Question answered by Ramin (source).

Some maps allow null as a value. For those maps, a lookup using this operator cannot distinguish between a key not being in the map, and the key being there with a null value.

This is from the get operator documentation for map. When you use containsKey it could be the case that the key exists but its value is null. You can use a local variable to store _cache[name] and check if it's null or not. Dart then can promote that local variable and not give you any errors. So your factory will look like this:

factory Person(String name) {
    final cached = _cache[name];
    if (cached != null) {
      return cached;
    } else {
      final person = Person.newPerson(name);
      _cache[name] = person;
      return person;
    }
}
DART FLUTTER
SHARE: