How to write a `ByteData` instance to a File in Da

2019-02-15 07:52发布

问题:

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?

回答1:

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.



标签: dart