How to get firebase storage image url to firestore database

1,304

you can used this function for upload image and get url from firebase

Future uploadFile(File file) async {
    StorageReference storageReference = FirebaseStorage.instance.ref().child(
        '${FirebaseStorageFolder.transactionDoc}/${Path.basename(file.path)}}');
    StorageUploadTask uploadTask = storageReference.putFile(file);

    var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
    print("done");
    return dowurl.toString();


  }
Share:
1,304
vindi96
Author by

vindi96

Updated on December 21, 2022

Comments

  • vindi96
    vindi96 11 months

    I'm trying to upload images to firebase storage and use that image url as metadata in firestore, however the image url is always null. Here is the codes

    how I get the picture

    File noticepic;
    Future getNotice()async{
    var tempImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      noticepic=tempImage ;
    });
    }
    

    how I upload it to firebase storage

    uploadNotice()async{
      var randomno=Random(25);
      final StorageReference firebaseStorageRef=FirebaseStorage.instance
      .ref().child('cisnotices/${randomno.nextInt(5000).toString()}.jpg');
        StorageUploadTask task = firebaseStorageRef.putFile(noticepic);
        StorageTaskSnapshot snapshottask =  await task.onComplete;
       String downloadUrl = await snapshottask.ref.getDownloadURL();
        noticeProvider.changePhotoUrl(downloadUrl.toString());
    
      setState(() {
        print('pic uploaded');
    
      });
    
    }
      NoticeProvider noticeProvider=NoticeProvider();
    

    This is the noticeprovider.dart

     changePhotoUrl(String value){
     _photoUrl=value;
     notifyListeners();
       }
    
      saveNotice(){
     var newNotice=Notice(userName: userName,userPost: userPost,photoUrl: photoUrl,
     date: date,noticeId: uuid.v4());
     firestoreService.saveNotice(newNotice);
     } 
    

    how i trigger the picture to be taken by pressing a icon button

     child: IconButton(
                           icon: Icon(Icons.add_photo_alternate),
                           color: Colors.grey[700],
                                iconSize: 40,
                                onPressed:(){
                                  getNotice().then((f) async => await uploadNotice());
    
                                 }
                                 ),