簡體   English   中英

Flutter:LateError(LateInitializationError:字段“設備”尚未初始化。)

[英]Flutter: LateError (LateInitializationError: Field 'device' has not been initialized.)

我想創建心率屏幕並從智能手表獲取數據(在 flutter_blue 上使用藍牙),我嘗試了很多方法,我不知道如何修復它,如何解決以下錯誤: 在此處輸入圖像描述

發生異常。 LateError(LateInitializationError:字段“設備”尚未初始化。)

這是我的代碼:

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')),
          
        ],
      ),
    );
  }
}

嘗試使用以下

 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);
      }
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM