Home > Back-end >  How to assign List<dynamic> to List<Khana>, where Khana is a model class in a parameter
How to assign List<dynamic> to List<Khana>, where Khana is a model class in a parameter

Time:01-08

Actually, I am trying to get data from firebase and I am suffering from the Error:

Expected a value of type List < Khana >, but got one of type 'List< dynamic >'

I am getting data from the firebase, my fetchData function is:

Future<void> fetchAndSetOrder() async {
    try {
      await collectionRef.get().then((querySnapshot) {
        for (var result in querySnapshot.docs) {
          debugPrint("${result.runtimeType}=> ${result.data()}");
          Orders newOrder = Orders.fromFirestore(result);
          debugPrint("\n new order : $newOrder");
          // _Order.add(newOrder);
          debugPrint("new order added");
          // _Order.add(Orders.fromMap(result as Map));
        }
      });
    } catch (e) {
      debugPrint("Error during Fetch:- $e");
    }
  }

and the Orders.fromFirestore constructor is:

factory Orders.fromFirestore(DocumentSnapshot<Object?> snapshot) {
    final data = snapshot.data() as LinkedHashMap<String, dynamic>;
    debugPrint("Inside From Firestore Function");
    return Orders(
      khana: data['khana'], // here is the error...
      orderNumber: data['orderNumber'],
      userId: data['userId'],
      paymentCash: data['paymentCash'],
      dateTime: data['dateTime'],
    );
  }

Orders class has:

class Orders{
  List<Khana> khana;  // this is another ModelClass
  String userId;
  int orderNumber;
  DateTime dateTime;
  bool paymentCash;
  Orders({
    required this.khana,
    required this.userId,
    required this.orderNumber,
    required this.dateTime,
    required this.paymentCash,
  });
}

so, the issue is how can I read List from the firestore as a List ? Any other possible way to solve this issue. My Khana Model is:

import 'dart:convert';

class Khana {
  String mealName;
  int id;
  int price;
  int quantity;
  Khana({
    required this.mealName,
    required this.price,
    required this.quantity,
    required this.id,
  });

  Map<String, dynamic> toMap() {
    final result = <String, dynamic>{};

    result.addAll({'mealName': mealName});
    result.addAll({'id': id});
    result.addAll({'price': price});
    result.addAll({'quantity': quantity});

    return result;
  }

  factory Khana.fromMap(Map<String, dynamic> map) {
    return Khana(
      mealName: map['mealName'] ?? '',
      id: map['id']?.toInt() ?? 0,
      price: map['price']?.toInt() ?? 0,
      quantity: map['quantity']?.toInt() ?? 0,
    );
  }

  String toJson() => json.encode(toMap());

  factory Khana.fromJson(String source) => Khana.fromMap(json.decode(source));
}

I am trying to read a List from the firestore snapshot.data(), it says it's return data type is List, and I want this list to be assigned to the List of my own ModelClass (i.e Khana), and I am not able to do that. I even tried

factory Orders.fromFirestore(DocumentSnapshot<Object?> snapshot) {
    final data = snapshot.data() as LinkedHashMap<String, dynamic>;
    debugPrint("Inside From Firestore Function");
    return Orders(
      khana: data['khana'] as List<Khana>, 
      orderNumber: data['orderNumber'],
      userId: data['userId'],
      paymentCash: data['paymentCash'],
      dateTime: data['dateTime'],
    );
  }

but got the same issue :(

CodePudding user response:

Change your khana to this

khana: List<Khana>.from(data['khana'].map((x)=>Khana.fromJson(x)));
  • Related