1

I receive the error The non-nullable local variable 'box' must be assigned before it can be used. for the following code.

int problemClass = -1;
problems.forEach((p) async {
      if (p.problemClassId != problemClass) {
        if (problemClass != -1)
          box.close();
        box = await Hive.openBox(kProblemBoxNames[p.problemClassId]!);
        problemClass = p.problemClassId;
      }
}      

I am opening a Hive box in the first iteration (box.close()cannot be executed because problemClass == -1). If problemClass does not change, the box remains unchanged in the 2nd iteration. However, if problemClass does change, the box currently open is closed and another box is opened.

How do I get the compiler to understand my logic?!

w461
  • 2,168
  • 4
  • 14
  • 40
  • 1
    You can fix your problem by declaring `box` as `late`. However, your logic isn't correct since `box.close()` will never be called; all iterations will execute before `problemClass` is set to a different value. [*Never* use `Iterable.forEach` with an `async` callback](https://stackoverflow.com/q/63719374/). You also will need to separately call `box.close()` after the final iteration. – jamesdlin Jul 06 '21 at 22:47
  • Thanks, that made a difference. I don't see why the box.close() will never be called, but if you are right, I will find out during debugging. One thing that make me wonder a few times: why do some respondents prefer to answer with a comment instead of an answer? – w461 Jul 07 '21 at 11:09
  • As I said, `box.close()` will not be called because `Iterable.forEach` is not meant to be used with `async` operations, and it is impossible for each iteration to wait for `Future`s from previous iterations to complete. Therefore `problemClass` will be -1 for all iterations. As for comment vs. answer: in this case, I didn't feel like writing a more extensive answer explaining *why*, and there likely are existing questions (and answers). – jamesdlin Jul 07 '21 at 11:24
  • got it. I already changed from `.forEach` to `for (p in xy)` – w461 Jul 07 '21 at 11:34

0 Answers0