0

Data on my firebase looks like this: enter image description here

I want to convert the LIST_OF_ALL_COLLEAGUES into a List but I am unable to figure out how to do it.

I have a user class which has this List colleagues field. My conversion code for user class looks like this:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:snagsnapper/Contants/constants.dart';
import 'package:snagsnapper/Data/colleague.dart';

class User {
  User ({
    this.name,
    this.dateFormat,
    this.listOfALLColleagues,
  });

  String name;
  String dateFormat='dd-MM-yyyy';
  List<Colleague> listOfALLColleagues;

  User.fromMap(DocumentSnapshot data)
      : this(
    name: data[NAME],
    dateFormat: data[DATE_FORMAT],
    listOfALLColleagues: List<Colleague>.from(data[LIST_OF_COLLEAGUES]),
  );

  Map<String, dynamic> toJSON() => {
    NAME : name,
    DATE_FORMAT : dateFormat,
    LIST_OF_COLLEAGUES : listOfALLColleagues,
  };

}

My Colleague class looks like the following:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:snagsnapper/Contants/constants.dart';

class Colleague {
  String name;
  String email;
  String phone;
  String uniqueID;

  Colleague({
    this.name,
    this.email,
    this.phone,
    this.uniqueID,
  });

  Colleague.fromMap(DocumentSnapshot data)
      : this(
    name: data[NAME],
    email: data[EMAIL],
    phone: data[PHONE],
    uniqueID: data[UID],
  );

  Map<String, dynamic> toJSON() => {
    NAME : name,
    EMAIL : email,
    PHONE : phone,
    UID : uniqueID,
  };
}

I have tried several methods I have seen online upto now but with no luck: I have tried:

listOfALLColleagues: List<Colleague>.from(data[LIST_OF_COLLEAGUES]),
listOfALLColleagues: List.from(data[LIST_OF_COLLEAGUES]),
listOfALLColleagues: List.castFrom(data[LIST_OF_COLLEAGUES]),
listOfALLColleagues: data[LIST_OF_COLLEAGUES] as List<Colleague>,
listOfALLColleagues: data[LIST_OF_COLLEAGUES]
        .map((value) {
          return Colleague.fromMap(value);
        }).toList(),

I know some of these are same things but I just want to mention them here.

2
  • Does this answer your question? Flutter Cloud Firestore Map<String, dynamic> error Commented Apr 29, 2020 at 19:37
  • Thanks. It seems I need to manually convert Colleague. But I am struggling to understand how to do it in code. Commented Apr 30, 2020 at 4:33

1 Answer 1

1

I managed to do it with Json-Serial library. I wasn't aware of this library earlier and it I found it so much easier this way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.