Upload image in flutter web

前端 未结 3 675
别跟我提以往
别跟我提以往 2021-01-03 16:37

Flutter web is still in technical preview but i want to pick an image from the disk and upload it to the server. Is there anyway to add HTML, JS to my flutter web project a

3条回答
  •  渐次进展
    2021-01-03 17:22

    This will do what you want for web. Just call it from any button and it will open the system dialog to chose the file.

    import 'dart:typed_data';
    import 'package:universal_html/prefer_sdk/html.dart';    
    import '../../../providers/form_provider.dart';
    
    Uint8List uploadedImage;
    
    startFilePickerWeb(ProviderForm formProvider) async {    
      InputElement uploadInput = FileUploadInputElement();
      uploadInput.click();
    
      uploadInput.onChange.listen((e) {
        // read file content as dataURL
        final files = uploadInput.files;
        if (files.length == 1) {
          final file = files[0];
          FileReader reader = FileReader();
    
          reader.onLoadEnd.listen((e) {
          //Here I send the imatge to my Provider 
            formProvider.setLogoEmpresa(reader.result);
          });
    
          reader.onError.listen((fileEvent) {
            print("Some Error occured while reading the file");
          });
    
          reader.readAsArrayBuffer(file);
        }
      });
    }
    

    The provider:

    class ProviderForm extends ChangeNotifier {
        Uint8List logoEmpresa;
        void setLogoEmpresa(Uint8List newFile) {
           logoEmpresa = newFile;
           notifyListeners();
        }
    }
    

    Then in your view you can render it like this, in case no imatge it show a attachement icon:

    Container(
          width: formProvider.logoEmpresa == null
              ? 70.0
              : 90.0,
          child: formProvider.logoEmpresa == null
              ? Icon(
                  Icons.attach_file,
                  size: 70.0,
                  color: kColorPrincipal,
                )
              : Image.memory(formProvider.logoEmpresa,
                  fit: BoxFit.fitWidth),
        ),
    

    If you have any question, please ask and I'll do my best to help.

提交回复
热议问题