简体   繁体   中英

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

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");
  }
}

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM