Friday, July 29, 2022

[FIXED] How to read bytes of a local image file in Dart/Flutter?

Issue

I would like to use a placeholder image file that I've added to my code as "assets/placeholder.png", but I'm getting a File not found error. This is how I'm doing it from the dartlang documentation...

var bytes = await new File('assets/placeholder.png').readAsBytes();
String base64 = CryptoUtils.bytesToBase64(bytes);

The bytes variable errors every time. How can I save the bytes of a locally saved image file?


Solution

With Flutter environment, you have to use AssetBundle if you want to access to your assets (https://flutter.io/assets-and-images/).

import 'package:flutter/services.dart' show rootBundle;


ByteData bytes = await rootBundle.load('assets/placeholder.png');


Answered By - Hadrien Lejard
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.