我遵循的是article中描述的教程。
可以在这里找到本文的代码:https://github.com/seamusv/event_channel_sample。
我基本上只是使用kotlin而不是java来做同样的事情。
在本机代码(MainActivity.kt)中:
class MainActivity: FlutterActivity() {
private val STREAM_TAG = "alarm.eventchannel.sample/stream";
private var timerSubscription : Disposable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
EventChannel(getFlutterView(), STREAM_TAG).setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
Log.w("TAG", "adding listener")
[email protected] = Observable.interval(0, 1, TimeUnit.SECONDS)
.subscribe (
{
Log.w("Test", "Result we just received: $it");
events.success(1);
}, // OnSuccess
{ error -> events.error("STREAM", "Error in processing observable", error); }, // OnError
{ println("Complete"); } // OnCompletion
)
}
override fun onCancel(arguments: Any?) {
Log.w("TAG", "adding listener")
if ([email protected] != null) {
[email protected]?.dispose()
[email protected] = null
}
}
}
)
}
}
在我的main.dart中,我执行以下操作:
int _timer = 0;
StreamSubscription _timerSubscription = null;
void _enableTimer() {
if (_timerSubscription == null) {
_timerSubscription = stream.receiveBroadcastStream().listen(_updateTimer);
}
}
void _disableTimer() {
if (_timerSubscription != null) {
_timerSubscription.cancel();
_timerSubscription = null;
}
}
void _updateTimer(timer) {
debugPrint("Timer $timer");
setState(() => _timer = timer);
}
在构建函数中,我还创建了一个按钮,然后在onPressed上调用_enableTimer()。
new FlatButton(
child: const Text('Enable'),
onPressed: _enableTimer,
)
现在,每当我现在按下按钮来调用_enableTimer()时,应用程序就会崩溃,并且我得到输出“设备的丢失连接” ...
自从文章于2017年12月以来,我是在做错什么还是这是Flutter的较新版本中的错误?
最佳答案
我的问题的解决方案基本上是在主线程中启动流:
class MainActivity: FlutterActivity() {
private val CHANNEL = "alarm.flutter.dev/audio"
private val STREAM_TAG = "alarm.eventchannel.sample/stream";
private var timerSubscription : Disposable? = null
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), STREAM_TAG).setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
Log.w("TAG", "adding listener")
[email protected] = Observable
.interval(1000, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe (
{
Log.w("Test", "Result we just received: $it");
events.success(it);
}, // OnSuccess
{ error -> events.error("STREAM", "Error in processing observable", error); }, // OnError
{ println("Complete"); } // OnCompletion
)
}
override fun onCancel(arguments: Any?) {
Log.w("TAG", "adding listener")
if ([email protected] != null) {
[email protected]?.dispose()
[email protected] = null
}
}
}
)
}