💮
Flutter で assets の中の画像を File として読み込む方法
image_picker を使って手に入れた画像がXFile として渡って来るので、それの動作確認用に画像を assets/ から読み込んだ時のメモ。
まずはこちらをインストール。getApplicationDocumentsDirectory
というパスを手に入れるための関数を使います。
flutter pub add path_provider
こんな感じで File として読み込むための関数を定義してあげます。
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
final file = File('${(await getApplicationDocumentsDirectory()).path}/$path');
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
後は読み込んじゃって
final File f = await getImageFileFromAssets('test.png');
こんな感じで使っちゃえば OK。
Image.file(File(file.path))
Discussion
ありがとうございます!参考にさせていただきました。
iOS 16 のSimulatorで試したのですが(私だけかもですが)、writeAsBytes()の前にfile.create()しないとfile pathが見つからない的なExceptionが発生しました。