registerReceiver function
注册广播接收器
- 用于接收sendBroadcast或sendIntentBroadcast发送的广播,
- 通过传入
actions
来监听特定的广播事件,如果actions为null则表示监听所有事件。 - 方法返回独立创建的Stream.isBroadcast为true类型的Stream。
- 监听广播后必须由监听者自己管理StreamSubscription并在离开时调用StreamSubscription.cancel注销广播接收。
StreamSubscription receiver;
@override
void initState() {
super.initState();
receiver = registerReceiver(['actionUserLogin','actionUserInfoChang
e','actionLogout']).listen((intent){
switch(intent.action){
case 'actionUserLogin': accountId = intent['accountId'];
break;
case 'actionUserInfoChang': nickname = intent['nickname'];
break;
case 'actionLogout': Navigator.pop(context);
break;
}
});
}
@override
void dispose(){
receiver.cancel();
super.dispose();
}
Implementation
Stream<ActionIntent> registerReceiver([List<String>? actions]) =>
_controller.stream
.where((intent) => actions?.contains(intent.action) ?? true);