Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show picked image with file_picker in web?

how can I show image picked by file_picker in web while the file path is null in web platform ?

If the path was not null, showing the image is too easy with Image.file(File):

Image.file(context.select<BlogProvider, File>((BlogProvider p) => p.image))

but It can not create File for image in web because browsers don't give file path and It's null.

Future<void> pickImage() async {
    /// If [withReadStream] is set, picked files will have its byte data available as a [Stream<List<int>>]
    /// which can be useful for uploading and processing large files.
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['jpg', 'jpeg'],
      withReadStream: true,
    );
    if (result != null) {
      PlatformFile file = result.files.single; //single means I am Picking just One file not more
      _blogImage = File(file.path);//Null in web ,but Ok in Android
      notifyListeners();
    } else {
      // User canceled the picker
    }

  }
like image 710
Zahra Avatar asked Oct 12 '25 00:10

Zahra


1 Answers

When withReadStream is set to true, selected image can be accessed as:

        file.readStream.listen((event) {
          _blogImage = Image.memory(event);
          notifyListeners();
        });

but when withReadStream is false:

        _blogImage = Image.memory(file.bytes);
        notifyListeners();

And although file.path is null in flutter for web, the file.name is set correctly and we can display it.

More info here

Another way (without file_picker package):

  import 'dart:html' as html;
  // ...

  void pickFile() {
    final input = html.FileUploadInputElement()..accept = 'image/*';
    input.onChange.listen((event) {
      if (input.files.isNotEmpty) {
          fileName = input.files.first.name; // file name without path!
          
          // synthetic file path can be used with Image.network()
          url = html.Url.createObjectUrl(input.files.first);
        });
      }
    });
    input.click();
  }
like image 86
Spatz Avatar answered Oct 14 '25 15:10

Spatz