将快照从firebase转换为模型类

3lxsmp7m  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(120)

我试图创建一个Future方法,返回类型为AddressModel,从Firestore获取。但我卡住了。
AddressModel类:

class AddressModel{
  int pinCode,contactNum;
  String fullName,apartment,city,state;
  String? area;
  String? landmark;

  AddressModel({
    required this.pinCode,
    required this.contactNum,
    required this.fullName,
    required this.apartment,
    required this.city,
    required this.state,
    this.area,
    this.landmark,
  });

  Map<String, dynamic> toMap() {
    return {
      'pinCode': pinCode,
      'contactNum': contactNum,
      'fullName': fullName,
      'apartment': apartment,
      'area': area,
      'landmark': landmark,
      'city': city,
      'state': state,
    };
  }

  factory AddressModel.fromMap(Map<String, dynamic> map) {
    return AddressModel(
      pinCode: map['pinCode'] as int,
      contactNum: map['contactNum'] as int,
      fullName: map['fullName'] as String,
      apartment: map['apartment'] as String,
      area: map['area'] as String,
      landmark: map['landmark'] as String,
      city: map['city'] as String,
      state: map['state'] as String,
    );
  }
}

未来方法:

Future<AddressModel?> getAddress(BuildContext context)async{
    try{
      DocumentSnapshot snapshot = await _fireStore.collection("users").doc(currentUser!.uid).get();
      
      //---------------Stuck Here----------------//
      
    }on FirebaseException catch(e){
      showSnackBar(context, e.code.toString());
      return null;
    }
  }

Firestore文档:

修复:(感谢大家的帮助)

QuerySnapshot snapshot = await _fireStore.collection("users").where("uId",isEqualTo: currentUser!.uid).get();

      if(snapshot.docs.isNotEmpty){
        return AddressModel.fromMap(snapshot.docs[0]['address']);
      }
      return null;
c6ubokkw

c6ubokkw1#

DocumentSnapshot有一个名为data的特性,因此使用

snapshot.data // this will return the object in type Map<String, dynamic>

然后使用AddressModel.fromMap来解析
会是这样的,如果你想在debug中看到:

Map<String, dynamic> response = snapshot.data;
AddressModel addressModel = AddressModel.fromMap(response);
return addressModel;

你也可以加入所有的元素:

return AddressModel.fromMap(snapshot.data)

你可以在pub firebase_firestore中看到文档:https://pub.dev/documentation/firebase/latest/firebase_firestore/DocumentSnapshot-class.html

相关问题