Flutter Web – get asset image as File()

Issue

I am using a third party library that requires I pass U8IntList to display an image in a PDF. Their examples has me obtain the image in a File and read the bytes out.

PdfBitmap(file.readAsBytesSync())

This system is great when I am obtaining an image from a server, but I want to display an image stored in local assets.

What I tried to implement was this code..

 Future<File> getImageFileFromAssets(String path) async {

    final byteData = await rootBundle.load('assets/$path');
    final file = File('${(await getTemporaryDirectory()).path}/$path');
    await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

    return file;
  }

Which returns the error ‘No implementation found for method getTemporaryDirectory on channel plugins.flutter.io/path_provider’.

If anyone knows how to get an Asset Image as File on web it would be greatly appreciated.

Solution

Why would you want to write byte data to a file just to read it again? Just directly pass your byte data to the constructor that requires it. This should be changed on both your web and mobile implementations as it will end up being far faster.

final byteData = await rootBundle.load('assets/$path');
PdfBitmap(byteData.buffer.asUint8List())

Answered By – Christopher Moore

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.