问题描述
我想在Flutter中将 File
转换为 ByteData
对象.像这样:
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;
我了解到 ByteData
构造函数接收字节长度的长度并将其初始化为0,所以我可以做类似 ByteData(file.readAsBytesStync().length);
,但是我该如何填充它们?我想念什么?
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?
推荐答案
在Dart 2.5.0或更高版本中,我认为以下方法应该有效:
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);
(在Dart 2.5.0之前, file.readAsBytesSync()
行应为:
(Prior to Dart 2.5.0, the file.readAsBytesSync()
line should be:
Uint8List bytes = file.readAsBytesSync() as Uint8List;
File.readAsBytes
/ File.readAsBytesSync 代码>
曾经被声明为返回 List< int>
,但是返回的对象实际上是 Uint8List
子类型.)
File.readAsBytes
/File.readAsBytesSync
used to be declared to return a List<int>
, but the returned object was actually a Uint8List
subtype.)
将字节作为 Uint8List
后,您可以提取其 ByteBuffer
并从中构造一个 ByteData
.
Once you have the bytes as a Uint8List
, you can extract its ByteBuffer
and construct a ByteData
from that.
这篇关于如何从文件中获取ByteData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!