skip to Main Content

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

2

Answers


  1. 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;
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search