Onetik Dz
Onetik Dz

Reputation: 51

Mapping nested objects from firebase document in flutter using fromMap

Good evening, I need some help in flutter when it comes to mapping nested objects.

Here I am getting a "Salon" document from firebase and I am mapping the data to it, knowing that the Agents data are "firebase references" to the Agents collection ex: /agents/id [you can check the image below], so basically what I'm doing is getting the reference then calling a custom getData() that maps on its turn agents data to an Agent instance and returns it as an item of a list of Agents.

So what I want is mapping the future List<Future < < Agent > > that results to the List < Agent > agents

firebase model

Here is what've done so far

class Salon {
  final String id;
  final String name;
  final String email;
  final String image;
  final String website;
  final String phoneNumber;
  
  final List<Agent> agents;
 



  Salon({
    this.id,
    this.name,
    this.email,
    this.image,
    this.website,
    this.phoneNumber,
    this.agents,
  
  });

  factory Salon.fromMap(Map data) {
    return Salon(
      id: data['id'] ?? '',
      name: data['name'] ?? '',
      website: data['website'] ?? '',
      email: data['email'] ?? '',
      image: data['image'] ?? 'default.png',
      phoneNumber: data['phoneNumber'] ?? '',
  
      agents: (data['agents'] as List ?? []).map((item) async {
        Document<Agent> agentRef = item;
        Agent agent = await agentRef.getData();
        return agent;
      }).toList(),
    
    );
  }
}

Upvotes: 1

Views: 370

Answers (1)

Yauhen Sampir
Yauhen Sampir

Reputation: 2104

You don't need to write fromMap and toMap by yourself. The flutter community already cared about it. Just use JsonSerializable package to automate this process. It already works with nested objects. What you need is make a request and then use something like that:

final data = await agentRef.getData();

final salon = Salon.fromJson(data);

Upvotes: 1

Related Questions