0

Why is there an error:

A value of type 'TestBloc?' can't be returned from the method 'createFromId' because it has a return type of 'TestBloc.

The map contains values of type TestBloc (not of type TestBloc?) so it is impossible to assign a null value.

class TestBloc {
  String id;
  TestBloc({
    required this.id,
  });
}

class TestBlocFactory {
  final Map<String, TestBloc> _createdElements = HashMap<String, TestBloc>();

  TestBloc createFromId(String id) {
    if (_createdElements.containsKey(id)) {
      return _createdElements[id]; // !! ERROR !!
    } else {
      TestBloc b = TestBloc(id: id);
      _createdElements[id] = b;
      return b;
    }
  }
}
MendelG
  • 14,885
  • 4
  • 25
  • 52
Piotr Temp
  • 385
  • 5
  • 12

2 Answers2

0

You may define you map as <String, TestBloc> but still _createdElements[id] may return a null value, because the id key may not available so it may return null but because you check it in your if condition you can use ! (as @MendelG said) or you can cast it like this:

if (_createdElements.containsKey(id)) {
  return _createdElements[id] as TestBloc; // <--- change this
} else {
  TestBloc b = TestBloc(id: id);
  _createdElements[id] = b;
  return b;
}
eamirho3ein
  • 16,619
  • 2
  • 12
  • 23
0

Since you are checking that the map contains the correct id with _createdElements.containsKey, you know for sure that it won't return null. So, it's safe to use the ! operator which says "I won't be null"

class TestBloc {
  String id;
  TestBloc({
    required this.id,
  });
}

class TestBlocFactory {
  final Map<String, TestBloc> _createdElements = HashMap<String, TestBloc>();

  TestBloc createFromId(String id) {
    if (_createdElements.containsKey(id)) {
      return _createdElements[id]!;
    } else {
      TestBloc b = TestBloc(id: id);
      _createdElements[id] = b;
      return b;
    }
  }
}

See also

MendelG
  • 14,885
  • 4
  • 25
  • 52
  • I know that "!" will do the job, but I didn't understand why is it necessary when types are strictly given. So I looked for definition of [] operator of Map class which is: ```V? operator [](Object? key);``` Operator [] can return null (even when value type is non nullable) if key is null. – Piotr Temp Dec 28 '22 at 18:45
  • @PiotrTemp I didn't fully understand, are you saying or asking? are you saying that it isn't safe to use `!` in this example? – MendelG Dec 28 '22 at 18:49
  • My question was why in Map there are non nullable values, but when we access them thay are nullable. Now I understand. Thanks for disscussion. – Piotr Temp Dec 28 '22 at 18:51
  • @PiotrTemp Got you. Would you consider marking which ever answer has helped you the most [as accepted](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) (Click on the checkmark next to the answer) – MendelG Dec 28 '22 at 19:13