Flutter firebase database.set(object) issue

3,939

Solution 1

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.

Solution 2

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.

Share:
3,939
Midhilaj
Author by

Midhilaj

I started coding life when I was studying in higher secondary class. Then I started to develop the application with "Visual Studio 2010". Opensource event in Kochin university was a turning point in my life which helped me to realize the power of open source. Then I started to use Ubuntu which helped me to learn a lot of tools, programming language, and framework. When I was in the 3rd semester in computer science and engineering, our new teacher forced me to develop an android app. From then I started to code in Android and I developed an app for our college. After getting the reviews, I realized that my skill is in coding. I spend more time in coding and now I can say that I am a professional programmer. I developed more than 20 apps. I focused on e-commerce app development and succeeded in that field. I also got 3 clients in e-commerce and successfully developed apps for them. I develop the admin website using angular2 since it helps to develop the website without refreshing for every action. All server request is done in the background and user feel the website like desktop software and in the future, I can make it as desktop software by using Electron (at that time open cart and PrestaShop admin website will refresh and take more time while performing any actions). My first server-side programming language is PHP (Rest API jacwright/RestServer and Slim Framework). I use firebase to develop 95% of my native app (Java, SQLite) and website(they are providing web hosting with SSL for free and it is highly secure and we don't need to worry about server-side script and server performance). My e-commerce app has the necessary features and an admin panel for admin to manage product, orders, delivery time, home page listing, category and category images, text field colors, etc I also successfully implemented an online payment gateway (instamojo) in my e-commerce apps I also developed an e-commerce app with the Flutter (Dart,sqflite ) using Shopify Rest API and implemented google map custom location picker. Flutter is amazing. It takes only a few days to develop the app with flutter when compared to app development time with android java. My technical guru is Google and stack overflow. My knowledge of coding life is from Google and StackOverflow. StackOverflow helped me to solve my doubts and issues during coding, at any time. I use Gitlab rather than GitHub because for the private project we need to pay for GitHub and my projects are not fully open-source. Gitlab allows publishing private project without any fee https://in.linkedin.com/in/midhilaj Flutter developer

Updated on December 08, 2022

Comments

  • Midhilaj
    Midhilaj over 1 year

    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());
          });
        }
      });
    }
    
    • Rubens Melo
      Rubens Melo over 5 years
      post your code/error
    • Midhilaj
      Midhilaj over 5 years
      updated please check it
    • Rubens Melo
      Rubens Melo over 5 years
      post your code, please.
    • Midhilaj
      Midhilaj over 5 years
      updated please check it
    • Feu
      Feu over 5 years
      productList is a List<Product>, right? create a toMap method that receives a Product and creates a map..
    • Slick Slime
      Slick Slime about 5 years
      @Feu so basically we cannot pass custom made Objects. Right?
    • Feu
      Feu about 5 years
      @Slick Slime, yes. Differently from the Java SDK, in flutter you have to do the "from/to" mapping. You can save List<int>, it will become an array in the database, but you have to use it carefully.