Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ByteData from a File

Tags:

flutter

dart

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?

like image 557
Mauricio Pastorini Avatar asked May 08 '19 15:05

Mauricio Pastorini


People also ask

How do you extract data from a byte file?

File file = getSomeCorrectFile(); Uint8List bytes = file. readAsBytesSync(); return ByteData. view(bytes. buffer);

How to convert file to byte stream in Java?

byte[] array = Files. readAllBytes(Paths. get("/path/to/file"));


1 Answers

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.

like image 82
jamesdlin Avatar answered Sep 27 '22 18:09

jamesdlin