Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

android - 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.

question from:https://stackoverflow.com/questions/65649212/firebase-flutter-cannot-write-data-to-database

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(); // <-----
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...