I want to convert a File to a ByteData object in flutter.
Something like this:
import 'dart:io';
File file = getSomeCorrectFile(); //This file is correct
ByteData bytes = ByteData(file.readAsBytesSync()); //Doesnt compile
return bytes;
I understood that ByteData constructor receives the length of the amount of bytes and initialize them with 0, so I could do something like ByteData(file.readAsBytesStync().length); but then how do I fill them?
What am I missing?
File file = getSomeCorrectFile(); Uint8List bytes = file. readAsBytesSync(); return ByteData. view(bytes. buffer);
byte[] array = Files. readAllBytes(Paths. get("/path/to/file"));
In Dart 2.5.0 or later, I believe that the following should work:
import 'dart:io';
import 'dart:typed_data';
...
File file = getSomeCorrectFile();
Uint8List bytes = file.readAsBytesSync();
return ByteData.view(bytes.buffer);
(Prior to Dart 2.5.0, the file.readAsBytesSync() line should be:
Uint8List bytes = file.readAsBytesSync() as Uint8List;
File.readAsBytes/File.readAsBytesSync used to be declared to return a List<int>, but the returned object was actually a Uint8List subtype.)
Once you have the bytes as a Uint8List, you can extract its ByteBuffer and construct a ByteData from that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With