Flutter – Adding data to Firebase Firestore with Model

Advertisements

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:

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

>Solution :

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

Leave a ReplyCancel reply