#flutter #dart #bluetooth-lowenergy
Вопрос:
Я использую BLE esp32 для получения данных с датчиков, но когда я хочу выполнить калибровку, получив данные с устройства BLE, это выдает мне эту ошибку в построителе потоков, который я использовал на экране настройки устройства. A Как только я нажимаю «Конфигурация», он переходит на страницу настройки устройства. Я хочу, чтобы до тех пор, пока я не получу значение 1 от BLE, он продолжал показывать этот экран
and once 1 comes it should go to the other screen to show a message and picture done like this and then automatically moves to Homepage after 2 seconds.
But it shows the bottom overflowed with the error msg «Bluetooth is not active», how can I avoid that? and jump for the next page? BLE is active as well since I checked the values were coming on another screen, but it is not happening on this screen for the connected device. Also the device done page it is not even going to Homescreen
I am new to FLutter that’s why i have no idea what i should do with it.
Code for Device Set up Screen:
import 'dart:typed_data';
import 'package:epicare/ConfDeviceDone.dart';
import 'package:epicare/ConfigurationScreen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'Homepage.dart';
class ConfDeviceSet extends StatefulWidget {
const ConfDeviceSet({Key key, this.device}) : super(key: key);
final BluetoothDevice device;
@override
_ConfDeviceSetState createState() => _ConfDeviceSetState();
}
class _ConfDeviceSetState extends State<ConfDeviceSet> {
// BLE
final String SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
//final String SERVICE_UUID = "0365a300-8d69-4066-80c7-554298a6ec5e";
//final String CHARACTERISTIC_UUID = "cf01c075-cb75-4dea-819e-2a79dd466bcb";
final String CHARACTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
bool isReady;
Stream<List<int>> stream;
List<int> lastValue;
List<double> traceDust = List();
@override
void initState() {
isReady = false;
discoverServices();
}
discoverServices() async {
List<BluetoothService> services = await widget.device.discoverServices();
services.forEach((service) {
if (service.uuid.toString() == SERVICE_UUID) {
service.characteristics.forEach((characteristic) {
if (characteristic.uuid.toString() == CHARACTERISTIC_UUID) {
characteristic.setNotifyValue(!characteristic.isNotifying);
stream = characteristic.value;
//print(stream);
lastValue = characteristic.lastValue;
//print(lastValue);
setState(() {
isReady = true;
});
}
});
}
});
}
_dataParser(List<int> data) {
var value = Uint8List.fromList(data);
print("stream.value: $value"); // stream.value: [33]
var hr = ByteData.sublistView(value, 0, 1);
print("Heart rate: ${hr.getUint8(0)}");
return hr.getUint8(0); // Heart rate: 33
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: const Color(0xffE5E0A1),
elevation: 0,
centerTitle: true,
title: Text(
"Configuration",
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
fontFamily: 'Montserrat',
fontWeight: FontWeight.normal,
),
),
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.black,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return ConfigurationScreen();
},
),
);
},
),
),
body: Column(
children: [
Container(
padding: EdgeInsets.only(top: 65),
alignment: Alignment.center,
child: Text(
'Device setting up...',
style: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w600,
fontSize: 17,
color: const Color(0xa8000000),
height: 1.3333333333333333,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Container(
padding: EdgeInsets.symmetric(vertical: 120),
child: const SpinKitFadingCircle(
color: const Color(0xffF1C40E),
size: 200,
),
),
StreamBuilder<List<int>>(
stream: stream,
initialData: lastValue,
builder: (BuildContext context, AsyncSnapshot<List<int>> snapshot) {
var currentValue = _dataParser(snapshot.data);
if (currentValue == 1) {
print("Test Conf 1");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return ConfDeviceDone(
device: widget.device,
);
},
),
);
}
},
),
],
),
);
}
}
Код для экрана «Готово» устройства
import 'package:epicare/Homepage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'ConfigurationScreen.dart';
class ConfDeviceDone extends StatefulWidget {
const ConfDeviceDone({Key key, this.device}) : super(key: key);
final BluetoothDevice device;
@override
_ConfDeviceDoneState createState() => _ConfDeviceDoneState();
}
class _ConfDeviceDoneState extends State<ConfDeviceDone> {
@override
void initState() {
// isReady = false;
// discoverServices();
var d = Duration(seconds: 2);
// delayed 5 seconds to next page
Future.delayed(d, () {
// to next page and close this page
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) {
return Homepage(device: widget.device);
},
),
(route) => false,
);
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: const Color(0xffE5E0A1),
elevation: 0,
centerTitle: true,
title: Text(
"Configuration",
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
fontFamily: 'Montserrat',
fontWeight: FontWeight.normal,
),
),
),
body: Column(
children: [
Container(
padding: EdgeInsets.only(top: 65),
alignment: Alignment.center,
child: Text(
'Device Configured Successfully!',
style: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w600,
fontSize: 15,
color: const Color(0xa8000000),
height: 1.3333333333333333,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Container(
padding: EdgeInsets.symmetric(vertical: 120),
child: Image.asset('assets/images/green-tick.gif'),
),
],
),
);
}
}
Комментарии:
1. ошибка заключается в том, что из streambuilder вы не возвращаете виджет . Да, вы возвращаете виджет, когда условие if выполнено, также выполните условие else
2. я использовал условие else раньше, но оно давало ту же ошибку, поэтому я удалил его
3. Кроме того, из-за построителя потоков другой экран не переходит на домашнюю страницу через 2 секунды?
4. как я вижу, и вы сказали да, потоковый конструктор вызывает это, но о возвращении на рабочий стол я не могу сказать
5. один раз попробуйте просто показать виджет в streambuilder, а не нажимать, чтобы проверить, вызывает ли он проблему или нет