How to get ByteData from a File

流过昼夜 提交于 2020-12-29 09:53:18

问题


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?


回答1:


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.




回答2:


Try this:

File file = getSomeCorrectFile(); 
ByteData bytes = await file.readAsBytes().then((data) => ByteData.view(data as ByteBuffer)); 
return bytes;



回答3:


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;


来源:https://stackoverflow.com/questions/56044473/how-to-get-bytedata-from-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!