readValue<T> method
Asynchronously retrieves the value of the characteristic.
This method provides a flexible way to read the characteristic's value from a BLE device
and interpret it as either a raw byte list (List<int>
) or as a UTF-8 decoded string (String
).
Generics are employed to allow the caller to specify the desired return type, either String
or List<int>
.
If you want the value as a string:
String value = await myChar.readValue<String>(address: 'device-address');
If you need the raw bytes:
List<int> bytes = await myChar.readValue<List<int>>();
If a type other than String
or List<int>
is used, an ArgumentError
is thrown.
Implementation
Future<T> readValue<T>({
Duration timeout = const Duration(seconds: 5),
}) async {
final BleCharacteristicValue characteristicValue =
await CentralPlatformInterface.instance.readCharacteristic(
characteristic: this,
timeout: timeout,
);
if (T == String) {
return utf8.decode(characteristicValue.value) as T;
} else if (T == BleCharacteristicValue) {
return characteristicValue as T;
} else if (T == List<int>) {
return characteristicValue.value as T;
} else {
throw ArgumentError(
'Unsupported return type $T. Supported types are String and List<int>',
);
}
}