can anyone tell why this giv me an error when I place the CountProvider out side the initState and build function and error go way when I place the CountProvider inside the initState and it also outside the build functionenter image description here
and the error is[ The instance member ‘context’ can’t be accessed in an initializer.
Try replacing the reference to the instance member with a different expression ]
2
Answers
As we can see here
So initState has access to the
context
of a Stateful Widget because between the creation of a State and the calling of initState, a BuildContext is already available to be passed.So
build is then called after initState and we have our render.
In that order, it is after the build has been called that any other method is called, so any such in your code may not have access to a context outside of the scope of an
initState
or abuild
methodI think you are trying to declare a variable which you want to access in both initState method and build method. I think you may declare the variable globally and initialize it in initState method.