【发布时间】:2022-01-18 07:22:50
【问题描述】:
我目前正在尝试使用 flutter_reactive_ble 将一些基本的蓝牙扫描功能实现到应用程序。 我也在使用颤振块进行状态管理。 现在我必须解决问题,我找到了多个蓝牙设备,但 UI 没有更新。当我使用打印命令跟踪正在发生的事情时,我看到状态更新正确,但 UI 只更新一次。
这里是 BLoc:
class BtConnectionBloc extends Bloc<BtConnectionEvent, BtConnectionState> {
final BtConnectionsRepository _repo;
late StreamSubscription _stream;
BtConnectionBloc(this._repo) : super(const DevicesState()) {
List<DiscoveredDevice> _devices = [];
on<StartScanningEvent>((event, emit) {
_stream = _repo.getDevices().listen((device) {
final knownDeviceIndex = _devices.indexWhere((d) => d.id == device.id);
if (knownDeviceIndex >= 0) {
_devices[knownDeviceIndex] = device;
} else {
_devices.add(device);
add(FoundDevices(deviceList: _devices));
}
});
});
on<EndScanningEvent>((event, emit) {
_stream.cancel();
_devices = [];
emit(const DevicesState());
});
on<FoundDevices>((event, emit) {
emit(DevicesState(deviceList: _devices));
});
}
}
这是我创建的存储库类:
class BtConnectionsRepository {
final PairedDevicesRepository _deviceRepo = PairedDevicesRepository();
final FlutterReactiveBle _ble = FlutterReactiveBle();
static BtConnectionsRepository get instance => BtConnectionsRepository();
Stream<DiscoveredDevice> getDevices() async* {
yield* _ble.scanForDevices(withServices: []);
}
void connectToSavedDevices() async {
PairedDevices _devices = await _deviceRepo.getPairedDevices();
for (SavedDevice device in _devices.savedDevices) {
_ble.connectToDevice(id: device.id);
}
}
}
在 UI 部分,我在 didChangeDependencies 覆盖中添加了一个事件,其中
context.watch<BtConnectionBloc>().add(StartScanningEvent());
具体的UI部分是:
BlocBuilder<BtConnectionBloc, BtConnectionState>(
buildWhen: (previousState, state) {
if(previousState.props.length != state.props.length){
return true;
}
else {
return false;
}
},
builder: (context, state) {
return Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.0826,
),
child: createDeviceList(state.props));
},
)
那里调用的函数如下所示:
Widget createDeviceList(List<DiscoveredDevice> devices) {
List<Widget> deviceWidgetList = [];
for (var device in devices) {
deviceWidgetList.add(PairingItem(
device: device,
onPressed: () {},
));
}
return Column(children: deviceWidgetList);
}
我完全不知道它为什么会这样,但我只是像第一次更新一样,显示了一些设备,但后来发现的每个设备都没有显示或导致 UI 更新。
【问题讨论】: