简体   繁体   中英

Firebase/Flutter - cannot write data to database

I am writing my Flutter App which requires users to upload certain images to Firebase. Everything is working flawlessly for authentication of users and storing images to Firebase storage. In the part when user is required to upload a picture with a description from his phone all I get is picture in my storage part of Firebase but no description and other metadata in my database .

I checked database rules and they are public and working fine.

This is the current code for image upload part that is working fine:

 void uploadStatusImage() async {
if (validateAndSave()) {
  final Reference postImageRef =
      FirebaseStorage.instance.ref().child("Post Images");
  var timeKey = new DateTime.now();

  final Task uploadTask =
      postImageRef.child(timeKey.toString() + ".jpg").putFile(sampleImage);

  var ImageUrl = await (await uploadTask).ref.getDownloadURL();

  url = ImageUrl.toString();

  print("Image URL = " + url);

  goToHomePage();
  saveToDatabase(url);
}

and this is the database part which is not working:

void saveToDatabase(url) {
var dbTimeKey = new DateTime.now();
var formatDate = new DateFormat('MMM d, yyyy');
var formatTime = new DateFormat('EEEE, hh:mm aa');

String date = formatDate.format(dbTimeKey);
String time = formatTime.format(dbTimeKey);

DatabaseReference ref = FirebaseDatabase.instance.reference();

var data = {
  "image": url,
  "description": _myValue,
  "date": date,
  "time": time,
};
ref.child("Posts").push().set(data);

VS code is not giving me any errors and app is working fine in my android emulator. Any help will be greatly appreciated. Thanks.

You might want to save to database before going to home page?

  void uploadStatusImage() async {
    if (validateAndSave()) {
      final Reference postImageRef =
          FirebaseStorage.instance.ref().child("Post Images");
      var timeKey = new DateTime.now();

      final Task uploadTask =
          postImageRef.child(timeKey.toString() + ".jpg").putFile(sampleImage);

      var ImageUrl = await (await uploadTask).ref.getDownloadURL();

      url = ImageUrl.toString();

      print("Image URL = " + url);

      saveToDatabase(url); // Switch positions
      goToHomePage(); // <-----
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM