How to receive data from Provider inside another provider

Issue

i’m wondering how to receive data from a Provider class called <Data> inside my provider class Player below. As you can see here in my example I have a play function which needs data and awaits a String. The data is inside a provider String called Provider.of<Data>(context, listen: false).url;

I’m getting error because of the context. There is no context and my way of implementing Provider.of<Data>(context, listen: false).url; is wrong. So my question: how to implement Provider.of<Data>(context, listen: false).url; the correct way? How to receive this data? Thank you for your help!

class Player with ChangeNotifier {

  String path;
  final url = Provider.of<Data>(context, listen: false).url;

  void setPlayList(videosList) {
    url = path;
  }

  Future play() async {
   //my function
   await player.play(path);

  playerState = PlayerState.playing;
   notifyListeners();
  }

}

Solution

You can use ChangeNotifierProxyProvider :

ChangeNotifierProxyProvider<Data, Player>(
          create: (_) => Player(),
          update: (_, data, player) => player..update(data),
        )

in your Player class:

class Player with ChangeNotifier {

  String path;
  String _url;

  void update(Data data) {
    _url = data.url;
  }

...

}

Answered By – Kijju

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *