在BLoC中添加一个StreamController来处理蓝牙状态,然后在BLoC中使用StreamBuilder进行视图构建。以下是一个示例代码:
class MyBloc extends Bloc {
final BluetoothController _bluetoothController = BluetoothController();
final _bluetoothStateController = StreamController();
Stream get bluetoothState => _bluetoothStateController.stream;
@override
Stream mapEventToState(SomeEvent event) async* {
if (event is BluetoothChangedEvent) {
final currentState = state;
yield currentState.copyWith(
bluetoothState: event.bluetoothState,
);
_bluetoothStateController.add(event.bluetoothState);
}
}
@override
Future close() {
_bluetoothStateController?.close();
return super.close();
}
}
class BluetoothWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: context.watch().bluetoothState,
builder: (context, snapshot) {
final bluetoothState = snapshot.data;
if (bluetoothState == BluetoothState.connected) {
return Text('蓝牙已连接');
} else if (bluetoothState == BluetoothState.disconnected) {
return Text('蓝牙已断开');
} else {
return CircularProgressIndicator();
}
},
);
}
}