Search code examples
flutterprovider

How to use provider data from place where no BuildContext available


I need to call a provider data from a class Which doesn't extend any state classes

class Services {

  static listenForMessage(){
    var handler = webSocketHandler((webSocket) {
    webSocket.stream.listen((message) {
      Provider.of<ProviderClass>(context).chatsList.clear();// context unavailable
      webSocket.sink.add("echo $message");
    });
  });

  serve(handler, 'localhost', 8080).then((server) {
    print('Serving at ws://${server.address.host}:${server.port}');
  });
  }
} 

But there is no context available in this class, how can I call this data without BuildContext


Solution

  • did you try to receive the context in the function arguments and send it where your function is required?

    static listenForMessage(context){...}