0
votes

Trying to upload images to firebase storage after picking images in flutter web as follows:

void uploadImage({@required Function(File file) onSelected}) {
    print('selecting image');
    InputElement uploadInput = FileUploadInputElement()
      ..accept = 'image/*'; //it will upload only image
    uploadInput.click();
    uploadInput.onChange.listen((event) {
      final file = uploadInput.files.first;
      final reader = FileReader();
      reader.readAsDataUrl(file);
      reader.onLoadEnd.listen((event) {
        onSelected(file);
      });
    });

    //selected image
  }

  void uploadStorage() {
    //upload selected image to Firebase storage
    final dateTime = DateTime.now();
    final path = 'CategoryImage/$dateTime';
    uploadImage(onSelected: (file) {
      if (file != null) {
        setState(() {
          _fileNameTextController.text = file.name;
          _imageSelected=false;
          _url = path;
        });
        Reference firebaseStorageRef = FirebaseStorage.instance.ref('CategoryImage/$dateTime').child(file.name);
        UploadTask uploadTask = firebaseStorageRef.putFile(file);
        uploadTask.whenComplete(() async{
          String imgUrl = await firebaseStorageRef.getDownloadURL();
        });
        // fb.storage().refFromURL('gs://flutter-grocery-app-ca3ef.appspot.com').child(path).put(file);
      }
    });
  }

But it returns following error:

error: The argument type 'File (where File is defined in C:\src\flutter\bin\cache\pkg\sky_engine\lib\html\html_dart2js.dart)' can't be assigned to the parameter type 'File (where File is defined in C:\src\flutter\bin\cache\pkg\sky_engine\lib\io\file.dart)'. (argument_type_not_assignable at [grocery_app_admin] lib\widgets\category\category_upload_widget.dart:180)

I looked at some solutions suggesting that there is a conflict between dart:html and dart:io so importing them separately but that didn't work either.

1

1 Answers

0
votes

There are a few different Classes under File - in this case you need to use dart:html - see below

import 'dart:async';
import 'package:firebase/firebase.dart' as fb;
import 'dart:html' as html;

String url;

Future<String> uploadProfilePhoto(html.File image, {String imageName}) async {
  try {
    //Upload Profile Photo
    fb.StorageReference _storage = fb.storage().ref('displayPhotos/$imageName');
    fb.UploadTaskSnapshot uploadTaskSnapshot = await _storage.put(image).future;
    // Wait until the file is uploaded then store the download url
    var imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
    url = imageUri.toString();
  } catch (e) {
    print(e);
  }
  return url;
}