skip to Main Content

I am learning Firebase and now I want to store my dummy data to Firebase collection,

I have a model class TransactionCategory which has three fields

  1. id 2. name 3. array of transactions

like TransactionCategory(id:’1′,name:’Shopping’,transactions:[])

here I want to make a collection "Transaction Category" and instead of storing transactions in a field I want it to store inside a child collection named ‘Transactions’

hope I am clear in explaining what I want…

Parent Collection : TransactionCategory and it has two field(id,name) and a child collection(transactions)

List<TransactionCategory> transactionCategoryList = [
  TransactionCategory(id: '1', name: 'Food',
      //this array should be store in child collection
      transactions: [
    Transaction(id: '1', title: 'Dinner', amount: 100),
    Transaction(id: '2', title: 'Breakfast', amount: 30),
    Transaction(id: '3', title: 'Dinner', amount: 230),
  ]),
  TransactionCategory(id: '2', name: 'General',
      //this array should be store in child collection
      transactions: [
    Transaction(id: '1', title: 'Milk', amount: 50),
    Transaction(id: '3', title: 'Detergent', amount: 299),
  ]),
  TransactionCategory(id: '3', name: 'Shopping', transactions:
  //this array should be store in child collection
  [
    Transaction(id: '1', title: 'Clothe', amount: 3000),
    Transaction(id: '2', title: 'Shoes', amount: 1200),
    Transaction(id: '3', title: 'Shoes', amount: 2200),
  ]),
];

Button(
  title: 'save Categories',
  onPressed: () async {
    //for saving transaction list into a child collection
    final _db = FirebaseFirestore.instance;
    
    //here i dont know what should i code
  },
),

I want to save dummy data like this format shown in image

enter image description here

2

Answers


  1. According to your last comment, if you want to add a new document inside the "Transactions" sub-collection, then you have to create a reference that points to the sub-collection:

    CollectionReference transactionsRef = FirebaseFirestore.instance
        .collection("TransactionCategories")
        .doc("1")
        .collection("Transactions");
    

    Now you can use this collection reference to add documents.

    Login or Signup to reply.
  2. If you want to add a new document inside the "TransactionCategory" sub-collection, then refer to this code

    final FirebaseFirestore _firestore = FirebaseFirestore.instance;    
    final CollectionReference _Collection =
            _firestore.collection('TransactionCategories/' + docId + "/Transactions");
    
    DocumentReference documentReferencer = _Collection.doc();
    
    Map<String, dynamic> data = <String, dynamic>{
      "Id": "1",
      "Name": "Food"
    };
    
    var result = await documentReferencer.set(data);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search