1
votes

Hello I have a Widget build(BuildContext context) {}.' I tried to initialize the provider outside and use it, but I getting the following error:


Tried to listen to a value exposed with provider, from outside of the widget tree.

This is likely caused by an event handler (like a button's onPressed) that called Provider.of without passing listen: false.

To fix, write: Provider.of(context, listen: false);

It is unsupported because may pointlessly rebuild the widget associated to the event handler, when the widget tree doesn't care about the value.

The context used was: LoginSelectPage(dependencies: [MediaQuery], state: _LoginSelectPageState#0e08d)


@override
  void initState() {
    // TODO: implement initState
    //registrationBloc = BlocProvider.of<RegistrationBloc>(context);
    super.initState();
    (() async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      bool res = prefs.getBool('autoLoginKey');

      SocketProvider provider = Provider.of<SocketProvider>(context);//This is where it matters.
}

In this case, how do we initialize the provider to use it?

2

2 Answers

1
votes

You can either set the provider inside the build method:

@override
  Widget build(BuildContext context) {
    SocketProvider provider = Provider.of<SocketProvider>(context);
    //Your code goes here   
}

or do as the console says and add "listen: false" to your provider:

@override
void initState(){
  SocketProvider provider = Provider.of<SocketProvider>(context, listen: false);
  //Your code
  super.initState();
}
1
votes

You can use your provider in the didChangeDependencies method. This method is also called immediately after initState and has access to the BuildContext.

@override
  void didChangeDependencies() {
    SocketProvider provider = Provider.of<SocketProvider>(context);

    super.didChangeDependencies();
}