Search code examples
imagefileshowflutter-web

Display selected image in Flutter Web


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


Solution

  • 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?