首页 > 解决方案 > 无法使用 SignalR 调用方法

问题描述

我正在创建一个应用程序并使用信号器,我能够连接到集线器,但是每次遇到此异常时都无法调用方法:Unhandled Exception: type 'GeneralError' is not a subtype of type 'Error' in type cast

这是我的代码:

var hubConnection;
String mobileSession;

Future<void> createSignalRConnection() async {
  hubConnection =
      new HubConnectionBuilder().withUrl(GLOBAL_BACKEND_SESSION_NEW).build();
  await hubConnection.start();
  logger.log(Level.INFO, "Connection successful");
  hubConnection.onclose((error) {
    logger.log(Level.INFO, "Connection Closed");
    createSignalRConnection();
  });
}

Future<bool> sendParingCode(String pairingCode) async {
  final result = await hubConnection
      .invoke("RequestPairing", args: [mobileSession, pairingCode]);
  logger.log(Level.INFO, "Pairing successful");
  return true;
}

void initSession() async {
  mobileSession = await hubConnection
      .invoke("InitSession");
  print(mobileSession);
  logger.log(Level.INFO, "Session init successful");
}

我在 PageState 中这样使用它:

void initState() {
    super.initState();
    createSignalRConnection();
    initSession();
  }

标签: flutterdart

解决方案


createSignalRConnection我认为您应该在调用调用方法之前等待完成。尝试这个:

@override
void initState() {
    super.initState();
    _asyncInitState();
}

Future<void> _asyncInitState() async {
    await createSignalRConnection();    // HERE: add await
    initSession();
}

推荐阅读