i am working with IOT device through flutterBluePlus library and it works based on Bluetooth (BLE),
i am listening to characteristics and want to update app state whenever i receive data.
is it possible ? explain me how to achieve
if not suggest me any other way to do so
updating app state variable through custom actions
Custom Code
- What have you tried so far?
FFAppState().myVariable = newValue;
i have tried with this but getting error
import 'dart:convert'; import 'package:flutter_blue_plus/flutter_blue_plus.dart'; Future<dynamic> parseBluetoothData(String deviceId) async { // Add your function code here! Map<String, List<int>> receivedDataMap = {}; try { // Get the FlutterBluePlus instance BluetoothDevice device = BluetoothDevice.fromId(deviceId); // Check the current connection state using BluetoothConnectionState BluetoothConnectionState connectionState = await device.connectionState.first; if (connectionState != BluetoothConnectionState.connected) { // Attempt to connect to the device if it's not already connected print("Attempting to connect to the device..."); await device.connect(autoConnect: true).catchError((e) { print("Connection failed: $e"); }); } // Recheck the connection state after attempting to connect connectionState = await device.connectionState.first; if (connectionState != BluetoothConnectionState.connected) { print("Failed to connect to the device."); } // Discover services on the device List<BluetoothService> services = await device.discoverServices(); // Set notifications for all characteristics of the services for (BluetoothService service in services) { for (BluetoothCharacteristic characteristic in service.characteristics) { try { // Set notification for each characteristic to listen for data changes await characteristic.setNotifyValue(true); // Listen for notifications and collect the data characteristic.value.listen((value) { print("data --> ${characteristic.uuid}: $value"); // Convert the received byte data to integer values and add to the map if (receivedDataMap.containsKey(characteristic.uuid.toString())) { receivedDataMap[characteristic.uuid.toString()]! .addAll(value.map((byte) => byte.toInt()).toList()); } else { receivedDataMap[characteristic.uuid.toString()] = value.map((byte) => byte.toInt()).toList(); } }); } catch (e) { print( "Error setting notifications for characteristic ${characteristic.uuid}: $e"); } } } // Wait for a specified duration to gather some data (adjust as needed) await Future.delayed( Duration(seconds: 2)); // Adjust duration for your use case // Return the collected data as a JSON string return jsonEncode(receivedDataMap); } catch (e) { print("Error listening to Bluetooth characteristics: $e"); return "{}"; // Return an empty JSON object on error } }
- Did you check FlutterFlow's Documentation for this topic?
- No
2
2 replies