Flutter:后期误差(后期初始化误差:字段“device”尚未初始化,)

9gm1akwq  于 2023-01-21  发布在  Flutter
关注(0)|答案(1)|浏览(161)

我想创建心率屏幕并从智能手表中获取数据(使用Blutooh对flutter_blue),我尝试了很多方法,我不知道如何修复它,如何做以下错误:

出现异常。最近错误(最近初始化错误:字段"device"尚未初始化。)
这是我的代码:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
class HeartRatePage extends StatefulWidget {
  @override
  _HeartRatePageState createState() => _HeartRatePageState();
}

class _HeartRatePageState extends State<HeartRatePage> {
  FlutterBlue flutterBlue = FlutterBlue.instance;
  late BluetoothDevice device;
  late BluetoothCharacteristic _heartRateMeasurementCharacteristic;
  StreamSubscription<List<int>>? _streamSubscription;

  @override
  void initState() {
    super.initState();

    flutterBlue.startScan(timeout: Duration(seconds: 4));

    flutterBlue.scanResults.listen((results) {
      if (results != null) {

        var foundDevice = results.firstWhere(
            (r) => r.device.name == 'Heart Rate',
            orElse: () => throw ('Cant find'));
        if (foundDevice != null) {
          connectToDevice(foundDevice.device);
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _streamSubscription?.cancel();
  }
  void connectToDevice(BluetoothDevice _device) async {
    device = _device;

    if(device != null){
    try {
      await device.connect();
      List<BluetoothService> services = await device.discoverServices();
      BluetoothService heartRateService = services.firstWhere(
          (s) => s.uuid.toString() == '0000180d-0000-1000-8000-00805f9b34fb',
          orElse: () => throw ('Heart rate service not found'));
      if (heartRateService != null) {
characteristic
        _heartRateMeasurementCharacteristic = heartRateService.characteristics
            .firstWhere((c) =>
                c.uuid.toString() == '00002a37-0000-1000-8000-00805f9b34fb',
                orElse: () => throw ('Heart rate measurement characteristic not found'));
        if (_heartRateMeasurementCharacteristic != null) {
receive updates
          _streamSubscription = _heartRateMeasurementCharacteristic.value
              .listen((value) {
            // Parse the heart rate value from the characteristic data
            int heartRate = value[1];
            print(heartRate);
            setState(() {
              _heartRate = heartRate;
            });
          });
        }
      }
    } on Exception catch (e) {
      print(e);
    }
  }
  }
  late int  _heartRate;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 245, 245, 245),
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios_new,color: Color(0xFF61D2A4)),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text('Heart Rate',style: TextStyle(fontFamily: 'Roboto',fontWeight: FontWeight.bold)),
        centerTitle: true,
        foregroundColor: Colors.black,
        backgroundColor: Colors.white,
      ),
      body: Column(

          children: <Widget>[
           device == null
               ? Center(child: Text('No device found'))
               : Center(child: Text('Heart rate: $_heartRate bpm')),
          
        ],
      ),
    );
  }
}
drnojrws

drnojrws1#

尝试使用以下

BluetoothDevice? device;

 void connectToDevice(BluetoothDevice _device) async {
    device = _device;

    if(device != null){
      try {
        await device?.connect();
        List<BluetoothService>? services = await device?.discoverServices();
        BluetoothService? heartRateService = services?.firstWhere(
                (s) => s.uuid.toString() == '0000180d-0000-1000-8000-00805f9b34fb',
            orElse: () => throw ('Heart rate service not found'));
        if (heartRateService != null) {

          _heartRateMeasurementCharacteristic = heartRateService.characteristics
              .firstWhere((c) =>
          c.uuid.toString() == '00002a37-0000-1000-8000-00805f9b34fb',
              orElse: () => throw ('Heart rate measurement characteristic not found'));
          if (_heartRateMeasurementCharacteristic != null) {

            _streamSubscription = _heartRateMeasurementCharacteristic.value
                .listen((value) {
              // Parse the heart rate value from the characteristic data
              int heartRate = value[1];
              print(heartRate);
              setState(() {
                _heartRate = heartRate;
              });
            });
          }
        }
      } on Exception catch (e) {
        print(e);
      }
    }
  }

相关问题