【问题标题】:How can I close a streamSubscription from a different class如何关闭来自不同类的 streamSubscription
【发布时间】:2021-09-05 11:31:15
【问题描述】:

我有 3 个不同的类,一个是全局类,另一个是 class1,另一个是 class2。在全局类中,我有两个位置流订阅的全局变量。

StreamSubscription<Location> rideStreamSubscription;
StreamSubscription<Location> backgroundSubscription;

class1我有这个方法调用来启动流。

void getLocationLiveUpdates() async {
await BackgroundLocation.startLocationService();
    backgroundSubscription = BackgroundLocation.getLocationUpdates((location) {
/////
}
  }

效果很好,现在当我转到class2 时,我想关闭backgroundSubscription 流并启动rideStreamSubscription

void getRideLocationLiveUpdates() async {
    await backgroundSubscription.cancel();
    await BackgroundLocation.stopLocationService();
    await BackgroundLocation.startLocationService();
    rideStreamSubscription= BackgroundLocation.getLocationUpdates((location) {
/////
}
  }

但我收到此错误

 [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The method 'cancel' was called on null.

我的问题是有没有其他方法可以做到这一点?如果我不关闭第一个流,则会出现错误

════════ Exception caught by widgets library ═══════════════════════════════════
Incorrect use of ParentDataWidget.
════════════════════════════════════════════════════════════════════════════════

但它没有显示它来自哪里。 我正在使用this

【问题讨论】:

  • 您在 backgroundSubscription 初始化之前调用了 backgroundSubscription.cancel()。如果backgroundSubscriptionnull,则使用backgroundSubscription?.cancel() 不执行任何操作,或者先明确检查它是否为null
  • @jamesdlin 我已经在class1 backgroundSubscription = BackgroundLocation.getLocationUpdates((location) { } 中初始化了backgroundSubscription 当我转到class2 时,我想关闭它并启动rideStreamSubscription。谢谢,我会做空检查。 .抱歉,如果我的问题不清楚。我已经更新了。
  • 您有代码来初始化它,但您不能保证在调用getRideLocationLiveUpdates 之前执行(并完成)该代码。该错误清楚地表明getRideLocationLiveUpdates被调用,而backgroundSubscription仍然是null,所以你必须检查。

标签: flutter dart location


【解决方案1】:

您的代码完全没问题,但问题是您在开始收听之前尝试取消订阅。

解决方案: 只需添加一个空检查: await backgroundSubscription.cancel(); (或使用空检查将取消移动到stopListening

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多