How to get ByteData from a 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.
in Dart 2.9:
import 'dart:io';
import 'dart:typed_data';
final file = getSomeCorrectFile(); // File
final bytes = await file.readAsBytes(); // Uint8List
final byteData = bytes.buffer.asByteData(); // ByteData
return byteData;
this is worked for me ...
Uint8List uint8list = Uint8List.fromList(File(path).readAsBytesSync())