#[SOLVED] Attributes Confusion

7 messages · Page 1 of 1 (latest)

plucky creek
#

class OrdersModel {
  String id, email, name, phone, status, user_id, address;
  int discount, total, created_at;
  List<OrderProductModel> products;

  OrdersModel({
    required this.id,
    required this.created_at,
    required this.email,
    required this.name,
    required this.phone,
    required this.address,
    required this.status,
    required this.user_id,
    required this.discount,
    required this.total,
    required this.products,
  });

  // Convert Appwrite's Document to OrdersModel
  factory OrdersModel.fromJson(Document doc, [Strings]) {
    final data = doc.data;
    return OrdersModel(
      id: doc.$id,
      created_at: data['created_at'] ?? 0,
      email: data['email'] ?? '',
      name: data['name'] ?? '',
      phone: data['phone'] ?? '',
      status: data['status'] ?? '',
      address: data['address'] ?? '',
      user_id: data['user_id'] ?? '',
      discount: data['discount'] ?? 0,
      total: data['total'] ?? 0,
      products: List<OrderProductModel>.from(data['products']?.map((e) => OrderProductModel.fromJson(e)) ?? []),
    );
  }

  // Convert a list of Documents to a list of OrdersModels
  static List<OrdersModel> fromJsonList(List<Document> docs) {
    return docs.map((doc) => OrdersModel.fromJson(doc)).toList();
  }
}

class OrderProductModel {
  String id, name, image;
  int quantity, single_price, total_price;

  OrderProductModel({
    required this.id,
    required this.name,
    required this.image,
    required this.quantity,
    required this.single_price,
    required this.total_price,
  });

  factory OrderProductModel.fromJson(Map<String, dynamic> json) {
    return OrderProductModel(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      image: json['image'] ?? '',
      quantity: json['quantity'] ?? 0,
      single_price: json['single_price'] ?? 0,
      total_price: json['total_price'] ?? 0,
    );
  }
}```
#

How can I create thus Product Attribute can any one tell me please!

marsh grove
plucky creek
#

Save the data in Json

marsh grove
# plucky creek Save the data in Json

correct me if I'm wrong, you want to save data in Json Format in appwrite database? or you just want to create a factory method to return as Json?

plucky creek
#

Factory Method!

marsh grove
#

ohh copy, you can just add this to your OrderProductModel

Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'image': image,
      'quantity': quantity,
      'single_price': single_price,
      'total_price': total_price,
    };
  }

and you can call it like this

final products = OrderProductModel(
  id: "id",
  name: "name",
  image: "image",
  quantity: 0,
  singlePrice: 0,
  totalPrice: 0,
);

final productJson = products.toJson();