我正在使用 FlutterReactiveBle 来“监听”和传输我的命令并发送自定义特征。因此,我决定在 Riverpod 中创建一个 StateProvider,用我的特征(蓝牙)侦听器中收到的数据填充字符串列表。
final bluetoothServiceProvider = Provider<BluetoothService>((ref) {
return BluetoothService();
});
final streamDataProvider = StateProvider<List<String>>((ref) {
return [];
});
final streamSubscriptionProvider = StateProvider.family<void, bool>((ref, onOff) {
final characteristicTX = QualifiedCharacteristic(
serviceId: SERVICE_UUID,
characteristicId: CHARACTERISTIC_TX_UUID,
deviceId: "60:A4:23:C9:10:10",
);
final socket = ref
.read(bluetoothServiceProvider)
.flutterReactiveBle
.subscribeToCharacteristic(characteristicTX)
.listen((event) {
ref.read(streamDataProvider.notifier).state = [
...ref.read(streamDataProvider.notifier).state,
"${DateTime.now()} - ${utf8.decode(event)}",
];
});
if (onOff) {
print("RESUME");
socket.resume();
print(socket.isPaused);
} else {
print("CANCEL");
socket.cancel();
print(socket.isPaused);
}
});
这是我的 HomeView,我可以在其中发送命令并在 ListView 中显示来自
streamDataProvider
的数据。
return Scaffold(
appBar: AppBar(title: const Text("APP")),
body: Column(
children: [
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
ref.read(streamSubscriptionProvider(true));
},
child: const Text("Turn on stream"),
),
const SizedBox(width: 20),
ElevatedButton(
onPressed: () async {
ref.read(streamSubscriptionProvider(false));
},
child: const Text("Turn off stream"),
),
],
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
await ref.read(bluetoothServiceProvider).getVersion(mine);
},
child: const Text("Send command 'Get version'"),
),
],
),
const SizedBox(height: 20),
Expanded(
child: Card(
margin: const EdgeInsets.all(10),
child: ListView.builder(
padding: const EdgeInsets.all(10),
itemCount: ref.watch(streamDataProvider).length,
itemBuilder: (BuildContext context, int index) {
return Text(
ref.watch(streamDataProvider)[index],
style: const TextStyle(fontSize: 8),
);
},
),
),
),
],
),
);
问题是我不明白如何用按钮停止或恢复
streamSubscription
。套接字永远不会被取消,并且我仍然在 ListView 中接收数据。
这是我用于 BLE 的库:flutter_reactive_ble。
List<T>
没有可用作原始家庭密钥的 ==
方法。您需要使用生成的提供程序,它可以解决这个问题,或者使用来自 fast_immutable_collections的
IList<T>
之类的东西。