skip to Main Content

Online I found an approach to query random document snapshots from firebase firestore. I need to add the retrieved data to a list. But I don’t really know how. I get the above written error " The argument type ‘QuerySnapshot<Object?>’ can’t be assigned to the parameter type ‘Recipe’" . Can anyone help me?

My code where I query and want to save the data:



String getRandomGeneratedId() {
  const int AUTO_ID_LENGTH = 20;
  const String AUTO_ID_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  
  const int maxRandom = AUTO_ID_ALPHABET.length;
  final Random randomGen = Random();
  
  String id = '';
  for (int i = 0; i < AUTO_ID_LENGTH; i++) {
    id = id + AUTO_ID_ALPHABET[randomGen.nextInt(maxRandom)];
     print('RandomID is $id');
  }
  return id;
  }

Future<List<Recipe>> getData() async {
    List<Recipe> dataList = [];
    CollectionReference myRef = FirebaseFirestore.instance.collection('recipes');

  // Retrieves 3 random data in a loop
    for (int i = 0; i < 3; i++) {

      
      String _randomIndex = getRandomGeneratedId();
       print('RandomIndex is $_randomIndex');
      QuerySnapshot querySnapshot = await myRef
        .where('id', isGreaterThanOrEqualTo: _randomIndex)
        .orderBy('id', descending: false)
        .limit(1)
        .get();
        print('QUERYSNAP is $querySnapshot');
      
        dataList.add(querySnapshot); //HERE I GET THE ERROR

          
    }

    return dataList;
  }

My Recipe Model class looks like this:

class Recipe {
  String? calories;
   String? carbs;
  String? fat;
   String? id;
  String? price;
  String? protein;
  int? servings;
   String? title;
   String? url;
   List? ingredients;
   List? instructions;

  Recipe({
    required this.calories,
    required this.carbs,
    required this.fat,
    required this.id,
    required this.price,
    required this.protein,
    required this.servings,
    required this.title,
    required this.url,
    required this.ingredients,
    required this.instructions,
  });

Map<String,dynamic> toJson() {
  return {
  'url': url,
  'title' : title,
  'price' : price,
  'calories' : calories,
  'carbs' : carbs,
  'fat' : fat,
  'id' : id,
  'protein' : protein,
  'servings' : servings,
  'ingredients' : ingredients,
  'instructions' : instructions,
};

2

Answers


  1. Chosen as BEST ANSWER

    I figured it out on my own. I had to change it to:

    dataList.addAll(querySnapshot.docs.map((d)=> Recipe.fromJson(d.data() as Map<String, dynamic>)));
    

  2. Try dataList.add(querySnapshot.docs[i]);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search