0

In Dart/Flutter, I'm trying to read bytes from a data file (2 bytes per value; on a mobile device) and convert to a double.

I have the below code:

fileToData(File filename)  {
  var bytes = filename.readAsBytesSync();
  return bytes.buffer.asInt16List().map((e) {
    print("Value: ${e.toDouble()}");
    return e.toDouble();
  }).toList();
}

The return List values are all 0.0; however, in the print statement I see the e.toDouble() is not 0.0 and is indeed the correct value expected. I just can't seem to return it.

For example:

I/flutter (10636): Value: 404.0
I/flutter (10636): Value: 356.0
I/flutter (10636): Value: 345.0
I/flutter (10636): Value: 297.0
I/flutter (10636): Value: 200.0
I/flutter (10636): Value: 164.0

Back the returned List<double> is:

I/flutter (10636): SIGNAL: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,.....

Any suggestions? Thanks.

maxwell79
  • 123
  • 1
  • 6
  • I don't see anything wrong with your code. Are you absolutely certain you're printing the correct list? – jamesdlin Feb 10 '21 at 04:47
  • Very sure. Rather than returning the list I've also just `print` it and always a list of all zeros. – maxwell79 Feb 10 '21 at 09:22
  • Please post a minimal, complete, reproducible example. I copied and pasted your `fileToData` function, added appropriate `import`s and `void main() => print(fileToData(File('/path/to/some/file')));` ran it from the command-line, and it worked fine. – jamesdlin Feb 10 '21 at 09:36
  • Also, it might be useful to know how long your lists are and if you're seeing the same number of elements printed out. If you're using `print`, be aware that Android and iOS can throttle and truncate excessive console spew. – jamesdlin Feb 10 '21 at 09:39
  • Evidently the code runs as expected on a desktop Linux (with the same data file) but not on an Android device in Flutter. – maxwell79 Feb 10 '21 at 09:52
  • I just tried the code with a sample Flutter application on Android, and it also runs fine. I strongly suspect that you are not observing what you think you are. There shouldn't be anything wrong with the code you've posted (although you should explicitly specify the function's return type); if you have problems, it's somewhere else in your code, which is why you should narrow it down to a minimal, reproducible example. – jamesdlin Feb 10 '21 at 10:19

1 Answers1

0

Always add explicit return data types, not adding a data type (AKA dynamic) can not always expect the result you want.

List<double> fileToData(File filename)  {
  var bytes = filename.readAsBytesSync();
  return bytes.buffer.asInt16List().map((e) {
    print("Value: ${e.toDouble()}");
    return e.toDouble();
  }).toList();
}

List<double> data = fileToData(file);
Kohls
  • 820
  • 7
  • 19