Riverpod : Access Provider in initState method

4.4k views Asked by At

Trying to read a streamProvider inside initState, but failed. Enlight me please, what am I doing wrong here?

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final userStream = context.read(userStreamProvider);
      print('user : $userStream'); // user : AsyncValue<Null>.loading()
    });
  }

So far, what I found that context.read(userStreamProvider) only works inside build(BuildContext context) method

2

There are 2 answers

0
Rémi Rousselet On BEST ANSWER

Your code works. The problem is, you are not waiting for the user to be loaded.

What you want is probably:

  @override
  void initState() {
    super.initState();
    context.read(userStreamProvider.last).then((user) {
      print('user $user');
    });
    
  }

By reading userStreamProvider.last, you will be able to wait for the user to be loaded. You can then use .then or await like with all futures.

2
Shahul hameed J On

I'm using latest river pod version . It's not support that context.read function for getting provide values in initstate. How to access provider in initstate using current version of riverpod.