1

I have a function like this:

Map<int, ChapterInfo> _chapterInfoMap = HashMap();

ChapterInfo? getChapterInfo(int id) {
  ChapterInfo? info = _chapterInfoMap[id];
  if (info == null) {
    // do some other thing to find info. if I still get null, throw an exception.
  }
}

So, if I don't catch any exception, “info" shouldn't be null. But how can I remove the "?"?

  • var info = _chapterInfoMap[id] as ChapterInfo; – bakboem Jan 08 '23 at 07:01
  • 2
    You shouldn't need to do anything. If your `if` block assigns a value to the local variable `info` and throws if it's still `null`, then the type system should be automatically promoting `info` to a non-nullable type afterward . If you're observing different behavior, please provide a minimal, complete example that reproduces the problem you're encountering. – jamesdlin Jan 08 '23 at 07:22
  • @jamesdlin Thanks for your advice. The problem.is solved. – 暮光之城管 Jan 08 '23 at 09:16

1 Answers1

0

Simply change the method signature:

ChapterInfo getChapterInfo(int id) {
  ChapterInfo? info = _chapterInfoMap[id];
  if (info == null) {
    // do some other thing to find info. if I still get null, throw an exception.
    
    throw Exception('ChapterInfo is null');
  }
  return info;
}
Rhisiart
  • 1,046
  • 12
  • 13