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