Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a `ByteData` instance to a File in Dart?

Tags:

dart

I am using Flutter to load an "asset" into a File so that a native application can access it.

This is how I load the asset:

final dbBytes = await rootBundle.load('assets/file'); 

This returns an instance of ByteData.

How can I write this to a dart.io.File instance?

like image 482
Renato Avatar asked May 01 '18 15:05

Renato


1 Answers

ByteData is an abstraction for:

A fixed-length, random-access sequence of bytes that also provides random and unaligned access to the fixed-width integers and floating point numbers represented by those bytes.

As Gunter mentioned in the comments, you can use File.writeAsBytes. It does require a bit of API work to get from ByteData to a List<int>, however.

import 'dart:async'; import 'dart:io'; import 'dart:typed_data';  Future<void> writeToFile(ByteData data, String path) {   final buffer = data.buffer;   return new File(path).writeAsBytes(       buffer.asUint8List(data.offsetInBytes, data.lengthInBytes)); } 

I've also filed an issue to make the docs on Flutter more clear for this use case.

like image 194
matanlurey Avatar answered Sep 26 '22 15:09

matanlurey