Home > Software engineering >  The method 'fromSnapshot' isn't defined for the type 'Patient' dart flutter
The method 'fromSnapshot' isn't defined for the type 'Patient' dart flutter

Time:06-09

trying to load data from firebase to a data table i got this error :

The method 'fromSnapshot' isn't defined for the type 'Patient'.

This is the function where i have this problem , it show on 'fromSnapshot'

Future loadMoreDataFromStream() async {
    final stream = collection.snapshots();

    stream.listen((snapShot) async {
      await Future.forEach(snapShot.docs, (DocumentSnapshot element) {
        final Patient data = Patient.fromSnapshot(element);
        if (!patients
            .any((element) => element.name == data.name)) {
          patients.add(data);
          addDataGridRow(data);
        }
      });

      updateDataGridDataSource();
    });
  }

and this is the class Patient that I call

class Patient{
  String? name ; 
  String? pass ; 
  String? image ; 
  String? genre ; 
  DateTime? birth ; 
Patient(this.name, this.pass, this.genre,this.birth,{this.reference});
DocumentReference? reference;
static fromSnapshot(DocumentSnapshot snapshot) {
    Patient _newPatient = Patient.fromJson(snapshot.data()! as Map<String, dynamic>);
    _newPatient.reference = snapshot.reference;
    return _newPatient;}
factory Patient.fromJson(Map<String, dynamic> data) =>
      Patient(
          data['name'],
          data['pass'],
          data['birth'],
          data['genre'],);
Map<String, dynamic> toJson() => _patientToJson(this);
@override
String toString() => 'name $name';
Patient _patientFromJson(Map<String, dynamic> json) {
  return Patient(
    json['name'],
    json['pass'],
    json['birth'],
    json['genre'],
  );}
Map<String, dynamic> _patientToJson(Patient instance) {
  return {
    'name' : instance.name,
    'pass': instance.pass,
    'birth': instance.birth,
    'genre': instance.genre,
  };}}

CodePudding user response:

Try adding a method instead:

static Patient fromSnapshot(DocumentSnapshot snapshot) {
    Patient _newPatient = Patient.fromJson(snapshot.data()! as Map<String, dynamic>);
    _newPatient.reference = snapshot.reference;
    return _newPatient;
}

CodePudding user response:

Make sure your class looks something like this:

class Patient {
  String id = 'id'; //Add any other variable you want.

  Patient();

  factory Patient.fromSnapshot(DocumentSnapshot snapshot) {
    Patient newPatient = Patient.fromJson(snapshot.data()! as Map<String, dynamic>);
    newPatient.reference = snapshot.reference;
    return newPatient;
  }

}

Or this:

class Patient {
  String id; //Add any other variable you want.

  Patient({required this.id});

  factory Patient.fromSnapshot(DocumentSnapshot snapshot) {
    Patient newPatient = Patient.fromJson(snapshot.data()! as Map<String, dynamic>);
    newPatient.reference = snapshot.reference;
    return newPatient;
  }

}
  • Related