1

I am trying to convert a Uint8List to a string using Dart (in a Flutter project). I am using the Flutter Android USB Serial plugin ( https://github.com/altera2015/usbserial)

The data are coming from a usb device and are returned from the library as a Stream.

If outputed as a string, it looks like:

[255,0,0,0,255....]

When I try:

String newTag = ascii.decode(asyncSnapshot.data);

I get the error :

FormatException:Invalid value in input: 255

I don't know how to solve this issue, my result should be :

"352206000079439"
gpasse
  • 4,380
  • 7
  • 44
  • 75
  • Why do you need to store arbitrary bytes as a `String`? – jamesdlin Aug 23 '19 at 17:26
  • I am using data coming from a usb device connected to the phone (serial). This device sends data to my flutter application. The type of the data is Uint8List. I need to retrieve the value. – gpasse Aug 23 '19 at 17:41
  • That doesn't explain why you need it as a `String` instead of keeping it as a `Uint8List`. – jamesdlin Aug 23 '19 at 20:26
  • The string is referenced in a database. Those values come from an electronic tag that I read using a RFID reader. The reader reads the tag, sends the value. It uses this value to query a database. – gpasse Aug 24 '19 at 13:30
  • Dart `String`s are expected to store valid UTF-16. Trying to store arbitrary data as a `String` is asking for trouble. If you need a `String` to use as a key into the database, then you will need to do something else, such as *encoding* your data to a `String`(e.g. base64) and using the encoded form instead. – jamesdlin Aug 24 '19 at 16:01

2 Answers2

1

Try this one;

List<int> list = 'someData'.codeUnits;
Uint8List bytes = Uint8List.fromList(list);
String string = String.fromCharCodes(bytes);
Murat Aslan
  • 1,446
  • 9
  • 21
  • 1
    I have tested your code and i get a string: "ŸŸŸŸŸŸŸŸ". But what i should get is "352206000079439" – gpasse Aug 23 '19 at 17:40
0

If data has compressed as a blob type.

Uint8List bytes = Uint8List.fromList(tcp_socket_blob_data);
var inflated = zlib.decode(bytes);
var data = utf8.decode(inflated);

More: flutter/dart: How to decompress/inflate zlib binary string in flutter

noveleven
  • 569
  • 7
  • 17