问题描述
我正在尝试订阅我的 BLE 设备特性并在我的手机屏幕上打印通知值。我知道代码很糟糕,但这是我的第一个 Flutter 项目,请耐心等待。
错误来自 StreamBuilder 小部件,问题应该是 utf8.decode(snapshot.data)
我也很乐意接受有关如何使代码更易于阅读和更高效的任何想法,因为目前这是我能做的最好的事情。
FlutterBlue FlutterBlue = FlutterBlue.instance;
BluetoothDevice device;
BluetoothState state;
BluetoothDeviceState deviceState;
StreamSubscription<ScanResult> subscription;
var myUUID = "11111815-0000-1000-8000-00805f9b34fb";
var myCharacteristicUUID = "00002aca-0000-1000-8000-00805f9b34fb";
var myDevice = "ESP32";
var currentValue;
class MyHomePage extends StatefulWidget {
MyHomePage({Key key,this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void scanForDevices() async {
if (FlutterBlue.isScanning != null) {
print("Scanning");
subscription = FlutterBlue
.scan(timeout: const Duration(seconds: 4))
.listen((scanResult) async {
if (scanResult.device.name == myDevice) {
print("found ESP32");
//Assigning bluetooth device
device = scanResult.device;
//After that we stop the scanning for device
stopScanning();
}
});
} else {
print("Already scanning");
}
print("Scan stopped");
}
void stopScanning() {
FlutterBlue.stopScan();
subscription.cancel();
connectToDevice();
}
connectToDevice() async {
//Flutter_blue makes our life easier
await device.connect();
print("ESP32 connected");
//After connection start dicovering services
discoverServices();
}
BluetoothCharacteristic c;
//This stream is for taking characteristic's value
//for reading data provided by device
Stream<List<int>> listStream;
discoverServices() async {
print("discovering services");
List<BluetoothService> services = await device.discoverServices();
//checking each services provided by device
services.forEach((service) {
if (service.uuid.toString() == myUUID) {
service.characteristics.forEach((characteristic) async {
if (characteristic.uuid.toString() == myCharacteristicUUID) {
//Updating stream to perform read operation.
listStream = characteristic.value;
await characteristic.setNotifyValue(!characteristic.isnotifying);
characteristic.value.listen((value) {
print(utf8.decode(value));
});
}
});
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),),body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
Text("Stream:"),StreamBuilder(
stream: listStream,initialData: "None",builder: (context,snapshot) {
// if i remove "utf8.decode(snapshot.data)" the error goes away
return Text(utf8.decode(snapshot.data));
},],floatingActionButton: FloatingActionButton(
onpressed: scanForDevices,tooltip: 'Scan',child: Icon(Icons.add),// This trailing comma makes auto-formatting nicer for build methods.
);
}
}
解决方法
您似乎正在尝试将字符串值传递到具有整数格式的列表中。将列表类型从整数更改为字符串。这可以解决问题。