Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter firebase database.set(object) issue

I have a class Product and it is in List plist Now I need to call the firebase database.set(plist) this is working with Java but when I tried to do it with flutter dart it showing error anybody have the solution for this problem From StackOverflow, I understand use database.set('{"a":"apple"}) but when I am dealing with List I can't use this solution

update error message

error called Invalid argument: Instance of 'Product'

My code

  String table_name="order";
  FirebaseAuth.instance.currentUser().then((u){
    if(u!=null){
      FirebaseDatabase database = FirebaseDatabase(app: app);
      String push=database.reference().child(table_name).child(u.uid).push().key;

      database.reference().child(table_name).child(u.uid).child(push).set( (productList)).then((r){
        print("order set called");

      }).catchError((onError){
         print("order error called "+onError.toString());
      });
    }
  });
}
like image 878
Midhilaj Avatar asked Jan 27 '23 22:01

Midhilaj


2 Answers

We cannot directly set object in Firebase. Unfortunately in Flutter there is no easy solution like java json. Data types that are allowed are String, boolean, int, double, Map, List. inside database.set().

We can have a look at the official documentation of Flutter https://pub.dev/documentation/firebase_database/latest/firebase_database/DatabaseReference/set.html

Try setting object like this

Future<bool> saveUserData(UserModel userModel) async {
await _database
    .reference()
    .child("Users")
    .child(userModel.username)
    .set(<String, Object>{
  "mobileNumber": userModel.mobileNumber,
  "userName": userModel.userName,
  "fullName": userModel.fullName,
}).then((onValue) {
  return true;
}).catchError((onError) {
  return false;
});

}

I hope this code will be helpful.

like image 85
Aman Raj Srivastava Avatar answered Feb 04 '23 10:02

Aman Raj Srivastava


Extending a little bit an answer given as a comment above

You basically have to create an auxiliary map beforehand:

Map aux = new Map<String,dynamic>();

And then iterate through the array that you have adding the corresponding map for each child that you want to add:

 productList.forEach((product){
    //Here you can set the key of the map to whatever you like
    aux[product.id] = product.toMap();
 });

Just in case, the function toMap inside the Product class should be something like:

Map toMap() {
  Map toReturn = new Map();
  toReturn['id'] = id;
  toReturn['name'] = name;
  toReturn['description'] = description;
  return toReturn;
}

And then, when you are calling the set function to save to firebase you can do something like:

.set({'productList':aux,})

Hope this was helpful to someone.

like image 28
Sergio Pardo Avatar answered Feb 04 '23 10:02

Sergio Pardo