😼
[Flutter] ByteData classをFile classに変換する方法
はじめに
- File(
String path
) - File.fromRawPath(
Uint8List rawPath
) - File.fromUri(
Uri uri
)
コンストラクタは執筆時点で上記3種類です。
つまりByteData class
をFile class
に直接変換する手段は存在しません。
そのため、writeAsBytes methodを活用します。
プログラム
ストレージ領域にアクセスするために、path_provider
ライブラリをプロジェクトに導入します。
path_providerを追加
$ flutter pub add path_provider
ByteData -> File
import 'dart:async';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';
Future<String> get getLocalPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> convertByteDataToFile(ByteData data) async {
final path = await getLocalPath;
final imagePath = '$path/image.png';
File imageFile = File(imagePath);
final buffer = data.buffer;
final localFile = await imageFile.writeAsBytes(buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
return localFile;
}
活用場面
私の場合Base64をデコードしFileに変換した時、データが破損しました。
データが破損
print(File.fromRawPath(base64.decode(String base64)));
// 実行結果
flutter: File: '����
そのため複雑なデータ変換実施時、破損を回避するのに便利だと思います。
参考文献
Discussion