Diego Valdés
 · Front-end dev.

Preview an image without uploading it to the server (My solution!)

Resolved

Currently, in this version of Flutterflow (August 2023), it is not possible to preview an image that we want to upload to the server later. Therefore, tutorials like this one https://www.youtube.com/watch?v=xofe79Vz0jM&t=93s are NOT USEFUL (It's illogical that it's not possible to preview an image without uploading it). Conversations with FF support yielded NO SOLUTION at all, neither a custom code that would work. As a result, I had to learn about Dart and the quirks that FF has.

THE SOLUTION involves two codes:

1.- First, a custom action that is capable of converting an FFUploadedFile (Bytes) into a base64 string.

import 'dart:convert';

Future<String?> convertImageFileToBase64(FFUploadedFile imageFile) async {
  List<int>? imageBytes = imageFile.bytes;
  if (imageBytes != null) {
    String base64Image = base64Encode(imageBytes);
    return base64Image;
  }
}

2.- Next, a custom widget capable of previewing an image from a base64 string, transforming it into a Uint8List type, and finally displaying it using an Image.memory.

import 'dart:convert';
import 'dart:typed_data';

class Base64Image extends StatefulWidget {
  const Base64Image({
    Key? key,
    this.width,
    this.height,
    required this.base64,
  }) : super(key: key);
  final double? width;
  final double? height;
  final String? base64;
  @override
  _Base64ImageState createState() => _Base64ImageState();
}

class _Base64ImageState extends State<Base64Image> {
  @override
  Widget build(BuildContext context) {
    Uint8List? imageBytes;

    imageBytes = widget.base64 != null ? base64Decode(widget.base64!) : null;

    return imageBytes != null
        ? Image.memory(
            imageBytes,
            width: widget.width,
            height: widget.height,
            fit: BoxFit.cover,
          )
        : Container();
  }
}

Now, in FF editor use custom action created, and pass in imageFile variable the output of block "Store Media for Upload"

FINALLY!! drag in FF editor the custom widget created, and pass the output of custom action created.

The result!!!!!

To write this use translator :c sorry. I am speak spanish. Greetings from Chile!!.

32
24 replies