Home > database >  Map an Array of objects from Firebase to List Flutter
Map an Array of objects from Firebase to List Flutter

Time:09-24

I'm trying to retrieve an array of objects from Firebase and store it in Flutter Object as a List.

This is the collection, Firebase,

Firebase

And this is the model class

class Merchant {
  String shopName;
  String address;
  String description;
  String thumbNail;
  LatLng locationCoords;

  Merchant( 
      {this.shopName,
      this.address,
      this.description,
      this.thumbNail,
      this.locationCoords});
}


final List<Merchant> merchant = [];      // Map it to This List

I'd like to map it into this list above

    final List<Merchant> merchant = [];  

CodePudding user response:

First add this method to your Merchant class:

Merchant.fromMap(Map<String, dynamic> map) {
    shopName = map['shopName'];
    address = map['address'];
    description = map['description'];
    thumbnail = map['thumbnail'];
    locationCoords = map['locationCoords'];
  }

This method will then be used to write the data into the Merchant Class/Struct.

Retrieving the data the could look something like the following:

import 'package:cloud_firestore/cloud_firestore.dart';

FirebaseFirestore _firestore = FirebaseFirestore.instance;

CollectionReference merchRef = _firestore.collection('merchants'));


Future<List<Merchant>> getAllMerchants() async {
  List<Merchant> merchantList = [];
  
  await merchRef.get().then((QuerySnapshot querySnapshot) {
    querySnapshot.docs.forEach((doc) {
      Merchant merchant = Merchant.fromMap({
        'shopName': doc['shopname'],
        'address': doc['address'],
        'description': doc['description'],
        'thumbnail': doc['thumbnail'],
        'locationCoords': doc['location'],
      });
      merchantList.add(merchant);
    });
  });

 return merchantList;
}


P.S.: Haven´t tried this out yet and you might need some parsing for locationCoords, since it is of type LatLng.

  • Related