'Why can't I use context.read in build(), but I can use Provider.of with listen: false?
It's stated in the docs that these are the same, and context.read is just a shortcut for Provider.of<x>(context, listen: false).
There's also an error in the console if I try to use context.read in a build method, but it doesn't explain the reason.
I also found this topic: Is Provider.of(context, listen: false) equivalent to context.read()? But it doesn't answer "why".
Solution 1:[1]
The problem is that you try to call context before the widget has finished building, to run your code after the widget has finished building provide your code to the post frame callback function.
For Example:
WidgetsBinding.instance.addPostFrameCallback((_) {
// your code in here
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | EricSchaefer |
