Flutter误差:无法将"BluetoothDevice?"类型的值赋给"BluetoothDevice"类型的变量

5sxhfpxr  于 2023-01-21  发布在  Flutter
关注(0)|答案(1)|浏览(137)

Flutter误差:"BluetoothDevice?"类型的值无法分配给"BluetoothDevice"类型的变量。请尝试更改该变量的类型,或将右侧类型强制转换为"BluetoothDevice"。

void initState() {
    super.initState();
    // Start scanning for devices
    flutterBlue.startScan(timeout: Duration(seconds: 4));
    // Listen for scan results
    flutterBlue.scanResults.listen((results) {
      // Find the heart rate device
      device = results.firstWhere((r) => r.device.name == 'Heart Rate',
                orElse: () => null)?.device;

      if (device != null) {
        flutterBlue.stopScan();
        connectToDevice();
      }
    });
  }
ego6inou

ego6inou1#

试试这个:

void initState() {
    super.initState();
    // Start scanning for devices
    flutterBlue.startScan(timeout: Duration(seconds: 4));
    // Listen for scan results
    flutterBlue.scanResults.listen((results) {
    if(results != null) {
       // Find the heart rate device
      device = results.firstWhere((r) => r.device.name == 'Heart Rate',
                orElse: () => null)!.device;

     }
      if (device != null) {
        flutterBlue.stopScan();
        connectToDevice();
      }
    });
  }

相关问题