I'm currently working with the package flutter_reactive_ble, but I'm struggling to make the connection consistent. Yesterday I figured that the problem would surely come from the :
if (connectionState.connectionState == DeviceConnectionState.connected)
because most of the time it comes out as "connecting", but I'm not sure how to wait till it's connected if it comes out as "connecting" without checking in a loop like a sleep. The goal here is to go fast so the Ux is good
I'm working on a Mac M1 and testing on Android
PS: The code is not clean, but the goal is to make it work.
Hope someone can help
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qrcode/enum/characteristic_enum.dart';
class CadenaData extends StatefulWidget {
CadenaData({Key? key}) : super(key: key);
@override
State<CadenaData> createState() => _CadenaDataState();
}
class _CadenaDataState extends State<CadenaData> {
final flutterReactiveBle = FlutterReactiveBle();
@protected
@mustCallSuper
void findCadena(BuildContext context) async {
flutterReactiveBle.connectToDevice(
id: "DC:30:FC:9F:45:91",
connectionTimeout: const Duration(seconds: 10),
).listen(
(connectionState) async {
if (connectionState.connectionState == DeviceConnectionState.connected) {
//doing stuff
} else {
print("connection failed\n $connectionState.connectionState");
};
},
onError: (error) {
print("error on connect $error");
},
);
}
I fixed my problem with a "StreamSubscription" receiving the result of the "FlutterReactiveBle.connectToDevice()"
And a switch case to manage the different outputs of the stream.
late StreamSubscription<dynamic> _currentConnectionStream;
_currentConnectionStream = flutterReactiveBle
.connectToDevice(
id: "DC:30:FC:9F:45:91",
connectionTimeout: const Duration(seconds: 15),
)
.listen(
(connectionState) async {
switch (connectionState.connectionState) {
case DeviceConnectionState.connecting:
print("-- Connecting to device --");
break;
case DeviceConnectionState.connected:
print(" -- Connected --");
break;
case DeviceConnectionState.disconnecting:
print("-- disconnecting --");
break;
case DeviceConnectionState.disconnected:
print("-- disconnected --");
break;
}
},
onError: (error) {
print("error on connect $error \n");
},
);