3

Since flutter web is in tech preview, none of the plugins are working.

I have a task to show image, which we select. I have following picker

_startFilePicker() async {
InputElement uploadInput = FileUploadInputElement();
uploadInput.multiple = true;
uploadInput.click();

uploadInput.onChange.listen((e) {
  // read file content as dataURL
  final files = uploadInput.files;
  if (files.length == 1) {
    final file = files[0];
    final reader = FileReader();

    reader.onLoadEnd.listen((e) {
      _handleResult(reader.result);
          });
          reader.readAsDataUrl(file);
        }
      });
      }

        void _handleResult(Object result) {
          setState(() {
            images.add(result);
          });
        }

result gives me output data:image/jpeg;base64,/9j/4AAQSkZJRg....

How can I display this output in Image Widget?

I tried using Image.memory(base64Decode(file)). But file could't be decoded. I suspect because it's not raw base64.

How could I convert this output to visible image? And how to deal with multiple images too?

Thank you

Dharman
  • 21,838
  • 18
  • 57
  • 107
zeromaro
  • 413
  • 4
  • 20

1 Answers1

6

In you base64 string, exclude "data:image/jpeg;base64," and only keep "/9j/4AAQSkZJRg..."

Paste your base64 string to online image converter https://codebeautify.org/base64-to-image-converter, to make sure your base64 string is correct

_base64 = "/9j/4AAQSkZJRg...";

decode with

Uint8List bytes = base64Decode(_base64);

and show image with

Image.memory(bytes);

you can also reference this How to convert BASE64 string into Image with Flutter?

chunhunghan
  • 34,833
  • 3
  • 38
  • 59
  • Thank you for your comment. Yes I took inspiration from this topic :) Is there a way to nicely extract base64 string or it's done only manually? – zeromaro Sep 05 '19 at 09:16
  • 1
    please reference this https://stackoverflow.com/questions/24935653/how-to-download-picture-and-convert-to-base64-correctly-in-dart – chunhunghan Sep 05 '19 at 09:19
  • You could use the **RegExp** class from dart:core ( https://api.dartlang.org/stable/2.5.0/dart-core/RegExp-class.html ) to remove the header automatically, not manually. – Constantin Sep 08 '19 at 00:26
  • To extract base64 string I simply take the substring starting from the comma like this: String _base64 = result.toString().split(',')[1]; – JDE10 Dec 27 '19 at 11:27