Home > Back-end >  Flutter - Adding data to Firebase Firestore with Model
Flutter - Adding data to Firebase Firestore with Model

Time:01-08

I am developing an app with Flutter and I want to add data to Firebase Firestore using model. I wrote the following code for this:

Model/Product.dart:

class Product {
  String? name;
  int? stock;
  String? price;
  String? getirPrice;
  String? trendyolPrice;
  Product({
    this.name,
    this.stock,
    this.price,
    this.getirPrice,
    this.trendyolPrice,
  });
}

Screens/HomePage.dart:

FirebaseFirestore db = FirebaseFirestore.instance;
// ...
Scaffold(
  body: Column(
    children: [
      ElevatedButton(
        child: Text("Ekle"),
        onPressed: () {
          db
              .collection("Products")
              .add({Product("Test", 1, "Test", "Test", "Test")});
        },
      ),
    ],
  ),
);

I am getting this error:

enter image description here

How can I resolve this error? Thanks in advance for your help.

CodePudding user response:

You are using named constructor,

Product({
    this.name,
    this.stock,
    this.price,
    this.getirPrice,
    this.trendyolPrice,
  });

therefor you need to create instance like

final modelClass = Product(
      name: "name",
      getirPrice: "price",
      price: "p",
      stock: 3,
      trendyolPrice: "ds");

the .add expect map data, so I am using dart-generator to create .toMap. Now the model class is


class Product {
  String? name;
  int? stock;
  String? price;
  String? getirPrice;
  String? trendyolPrice;
  Product({
    this.name,
    this.stock,
    this.price,
    this.getirPrice,
    this.trendyolPrice,
  });

  Map<String, dynamic> toMap() {
    final result = <String, dynamic>{};

    if (name != null) {
      result.addAll({'name': name});
    }
    if (stock != null) {
      result.addAll({'stock': stock});
    }
    if (price != null) {
      result.addAll({'price': price});
    }
    if (getirPrice != null) {
      result.addAll({'getirPrice': getirPrice});
    }
    if (trendyolPrice != null) {
      result.addAll({'trendyolPrice': trendyolPrice});
    }

    return result;
  }

  factory Product.fromMap(Map<String, dynamic> map) {
    return Product(
      name: map['name'],
      stock: map['stock']?.toInt(),
      price: map['price'],
      getirPrice: map['getirPrice'],
      trendyolPrice: map['trendyolPrice'],
    );
  }

  String toJson() => json.encode(toMap());

  factory Product.fromJson(String source) =>
      Product.fromMap(json.decode(source));
}

And upload like

ElevatedButton(
  child: Text("Ekle"),
  onPressed: () {
    final modelClass = Product(
        name: "name",
        getirPrice: "price",
        price: "p",
        stock: 3,
        trendyolPrice: "ds");
    db.collection("Products").add(modelClass.toMap());
  },
),

More about using using-constructors and firestore/manage-data/add-data

CodePudding user response:

You can only pass Map<String,dynamic> object to firebase, but you are passing your custom object. to sort this up u need to create fromJson and toJson methods inside your object to parse the data.

I have added toJson below for u.

class Product {
  String? name;
  int? stock;
  String? price;
  String? getirPrice;
  String? trendyolPrice;
  Product({
    this.name,
    this.stock,
    this.price,
    this.getirPrice,
    this.trendyolPrice,
  });
  Map<String, dynamic> toJson(){
    Map<String,dynamic> json ={};
    json['name']  = name;
    json['stock']  = stock;
    json['price']  = price;
    json['getirPrice']  = getirPrice;
    json['trendyolPrice']  = trendyolPrice;
    return json;
  }
}

Now simply call

db.collection("Products").add({Product("Test", 1, "Test", "Test", "Test").toJson()});

Hope it helps.

  • Related