skip to Main Content

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

enter 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


  1. As we can see here

    The framework associates State objects with a BuildContext after
    creating them with StatefulWidget.createState and before calling
    initState

    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

    1. The State is created by StatefulWidget.createState

    State objects are created by the framework by calling the
    StatefulWidget.createState method when inflating a StatefulWidget to
    insert it into the tree.

    1. A context is associated with the State.
    2. The initState is called which also then gains access to the context.

    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 a build method

    Login or Signup to reply.
  2. I 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.

    class_HomePageState extends State<HomePage>
    var CountProvider; //Declare variable here
    
    @override
    void initState() {
    // TODO: implement initState
        super.initState();
        CountProvider = Provider.of<countProvider>(context, listen: false); // Initialize the variable here
    
        Timer.periodic(Duration(seconds: 0), (timer) { 
            CountProvider.IncraceCount(); 
        }); // Timer.periodic
    }
    @override
    Widget build(BuildContext context) {
    ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search