简体   繁体   中英

Flutter Firestore Stream error "as required by the closure's context."

I'm getting the following error not sure why The return type 'List<DogModel>' isn't a 'DogModel', as required by the closure's context.

Here is my Firestore service file where I get the Stream

Stream<DogModel> getDogs(String uid) {
return dogCollection.where('userId', isEqualTo: uid).snapshots().map(
      (snapshot) => snapshot.docs
          .map((document) => DogModel.fromFire(document))
          .toList(),
    );

}

Here is my model

part 'dog_model.g.dart';

enum DogGender {
  male,
  female,
}
enum DogWeight {
  kg,
  lbs,
}

enum DogStatus {
  active,
  training,
  injured,
  retired,
}

@JsonSerializable(explicitToJson: true)
class DogModel {
  String? dogImage;
  String dogName;
  DogBreed? breedInfo;
  @JsonKey(fromJson: dateTimeFromTimestamp, toJson: dateTimeAsIs)
  DateTime? dogBirthday;
  double? dogWeight;
  DogWeight? weightType;
  DogGender? dogGender;
  List<String>? dogType;
  DogStatus? dogStatus;
  bool? registered;
  String? dogChipId;
  @JsonKey(fromJson: dateTimeFromTimestamp, toJson: dateTimeAsIs)
  DateTime? createdAt;
  DogStats? dogStats;
  @JsonKey(ignore: true)
  String? id;
  String? userId;

  DogModel({
    required this.dogImage,
    required this.dogName,
    required this.breedInfo,
    required this.dogBirthday,
    required this.dogWeight,
    required this.weightType,
    required this.dogGender,
    required this.dogType,
    required this.dogStatus,
    required this.registered,
    this.dogStats,
    this.dogChipId,
    this.createdAt,
    this.userId,
    this.id,
  });

  factory DogModel.fromFire(QueryDocumentSnapshot snapshot) {
    return DogModel.fromJson(snapshot as Map<String, dynamic>);
  }

  // JsonSerializable constructor
  factory DogModel.fromJson(Map<String, dynamic> json) =>
      _$DogModelFromJson(json);

  // Serialization
  Map<String, dynamic> toJson() => _$DogModelToJson(this);
}

If I do Stream<Object> its fine

The getDogs function body is returning a List<DogModel> but the function definition is Stream<DogModel> . So change the definition to Stream<List<DogModel>> as follow:

// fix this   ↓
Stream<List<DogModel>> getDogs(String uid) {
return dogCollection.where('userId', isEqualTo: uid).snapshots().map(
      (snapshot) => snapshot.docs
          .map((document) => DogModel.fromFire(document))
          .toList(), // <~~~~ you're returning a list here 
    );

You have defined the return type of method getDogs() as Stream<DogModel> whereas your method returns Stream<List<DogModel>> , that is, it return a List of DogModel s. So your getDogs() method declaration should be like this:

Stream<<List<DogModel>> getDogs(String uid) {
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM