首页 > 解决方案 > How can I access an instance of an object in different classes / pages without a widget tree context?

问题描述

I am trying to access an instance of an RtcEngine object for AgoraIO from another class/page that doesn't have a widget tree, and therefore no context to refer to with Provider.

First I'm calling initPlatformState() from this class in order to initialize the RtcEngine engine:

class Game extends StatefulWidget {

  @override
  _GameState createState() => _GameState();
}

class _GameState extends State<Game> implements GameListener {

  @override
  void initState() {
    super.initState();
   Agora().initPlatformState(widget.playerId);
  }
}

initPlatformState initializes the RtcEngine by creating an instance called engine that I need to use later on to call other methods. This class also contains the method I want to call later using the same instance to adjustVolume...

class Agora {
  RtcEngine engine;
// Initialize the agora app
  Future<void> initPlatformState(int playerId) async {

    RtcEngine engine = await RtcEngine.create(APP_ID);
  }
  void adjustVolume(int uid, int volume) {
   
    engine.adjustUserPlaybackSignalVolume(uid, volume);
   
  }
}

This is the class that I want to call adjustVolume from. I was considering using Provider to pass the instance to this class but it extends another class and it doesn't have a widget tree with context so I'm not sure how thats possible or if there is a better way.

class Remote extends Component {

final int id;

Remote(this.id);

@override
void update() {
      //this is where I'm trying to access the engine instance that was created to call adjustUserPlaybackSignalVolume method

 }
}

Any suggestions on how to reuse that instance of "engine" given my situation would be greatly appreciated!

标签: flutteragora.io

解决方案


推荐阅读