Home > Net >  How to read values from txt file as Bytes using Flutter?
How to read values from txt file as Bytes using Flutter?

Time:09-28

actually I want to read values from .txt file and send them to a card stm32 via bluetooth with Byte format. I tried this solution but the values wasn't sent correctly. And I got this exception : type 'Future' is not a subtype of type 'List'

This is the code:

  localPath() async {
    String textasset = "assets/112936-bluetooth.txt";
    String text = await rootBundle.loadString(textasset);
    print(int.parse(text));
    return int.parse(text);
  }

Here's where I call the function:

     onWritePressed: () {
                      for (int i = 0; i < 4; i  )
                        c.write(localPath(), withoutResponse: true);
                    },

this is an example for some values in the .txt file: 0x00, 0xAA, 0x00, 0x03, 0x2F, 0x2F, 0xCC, 0xAA, 0x00, 0x0F, 0x2A Thanks in advance for your help

CodePudding user response:

You are passing a Future instead of list to a method write. So change your code like this

onWritePressed: () {
    for (int i = 0; i < 4; i  ){
        localPath().then((val) => c.write(val, withoutResponse: true));
    }
},

For more info on Future, head to future.dev

CodePudding user response:

Your localPath function is returning a Future because it is async. You need to wait for it to resolve. Also, as written that Future will resolve to an int, not List<int>, so that needs to be fixed as well.

Future<List<int>> localPath() async {
  final textasset = "assets/112936-bluetooth.txt";
  final text = await rootBundle.loadString(textasset);
  final bytes = text //
    .split(',')
    .map((s) => s.trim())
    .map((s) => int.parse(s))
    .toList();
  print(bytes);
  return bytes;
}

Then in your handler:

onWritePressed: () async {
  final bytes = await localPath();
  for (int i = 0; i < 4; i  ) {
    c.write(bytes, withoutResponse: true);
  }
},
  • Related