1

There is a way to get firestore data for example " User information" into user model class in flutter? This is my User Class:


class Users {
  final int id;
  final String firstName;
  final String lastName;
  final String emailAddress;
  final String imageProfile;

  const Users({
    this.id,
    this.firstName,
    this.lastName,
    this.emailAddress,
    this.imageProfile,

  });

}

final Users currentUser = Users(
  id: 'GET_DATA_FROM_FIRESTORE'/// firebaseUSer.currentUserUID
  firstName: 'GET_DATA_FROM_FIRESTORE',
  lastName: 'GET_DATA_FROM_FIRESTORE',
  emailAddress: 'GET_DATA_FROM_FIRESTORE',
  imageProfile: 'GET_DATA_FROM_FIRESTORE',
);

then pass the data with currentUser.firstName etc.. to other widgets. the data I need to retrieve into this class is created into SignuUp form in flutter and pushed to firestore collection

Tizi Dev
  • 301
  • 6
  • 19
  • 1
    It doesn't look like you've made an attempt to query Firestore yet. Start with that using the [documentation](https://firebase.flutter.dev/docs/firestore/usage/), then once you have data from a document, it should be clear how to put that into a data class. – Doug Stevenson Dec 20 '20 at 17:33

1 Answers1

1

I used this in my project.I hope that will helpful.

Model Class

class Message{
  String id;
  String message;
  String senderId;
  Timestamp timeStamp;
  bool isMedia;
  Message({this.id,this.message,this.senderId,this.timeStamp,this.isMedia});
  factory Message.fromSnapshot(DocumentSnapshot snapshot){
    return Message(
      id:snapshot.id,
      message: snapshot.data()['message'],
      senderId: snapshot.data()['senderId'],
      timeStamp: snapshot.data()['timeStamp'],
      isMedia: snapshot.data()['isMedia'],
    );
  }
  Map<String, dynamic> toJson() =>
  {
    'message': message,
    'senderId': senderId,
    'isMedia': isMedia,
    'timeStamp': DateTime.now(),
  };
}

Service Class

*Initial

  final FirebaseFirestore _fBaseFireStore = FirebaseFirestore.instance;
  CollectionReference _collectionRef;
  MessageService() {
    _collectionRef = _fBaseFireStore.collection('Conversation');
  }

*Get datas from firestore

    Stream<List<Message>> getMessages(String conversationId) {
    var ref = _collectionRef
        .doc(conversationId)
        .collection('messages');
    return ref.snapshots().map(
        (event) => event.docs.map((e) => Message.fromSnapshot(e)).toList());
  }

*Write data to firestore

  Future<void> sendMessage(Message message, String conversationId) async {
    var ref = _collectionRef.doc(conversationId).collection('messages');
    await ref.add(message.toJson());
  }
Mevlüt Gür
  • 155
  • 1
  • 10