Recently, I started working on a Flutter app, specifically a payment bill app, in which I needed to cast a `List<dynamic>` to a `List<Object>`. I have successfully completed this task, and in this post, I will discuss how you can convert a `List<dynamic>` to a `List<Object>` in Flutter.
class Order {
int id;
String productName;
String productDescription;
double soldPrice;
int quantity;
DateTime createdAt;
Order({
required this.id,
required this.productName,
required this.productDescription,
required this.soldPrice,
required this.quantity,
required this.createdAt,
});
}
void main() {
// Suppose we have a list of dynamic objects representing orders
List<dynamic> dynamicOrders = [
{
'id': 1,
'productName': 'Product 1',
'productDescription': 'Description 1',
'soldPrice': 10.0,
'quantity': 2,
'createdAt': DateTime.now(),
},
{
'id': 2,
'productName': 'Product 2',
'productDescription': 'Description 2',
'soldPrice': 15.0,
'quantity': 1,
'createdAt': DateTime.now(),
},
];
// We want to cast this list of dynamic objects to a list of Order objects
List<Order> orders = dynamicOrders.map((dynamic order) {
return Order(
id: order['id'],
productName: order['productName'],
productDescription: order['productDescription'],
soldPrice: order['soldPrice'],
quantity: order['quantity'],
createdAt: order['createdAt'],
);
}).toList();
// Now 'orders' contains a list of Order objects
}
class Order {
int id;
String productName;
String productDescription;
double soldPrice;
int quantity;
DateTime createdAt;
Order({
required this.id,
required this.productName,
required this.productDescription,
required this.soldPrice,
required this.quantity,
required this.createdAt,
});
}
List<Order> convertDynamicListToOrderList(List<dynamic> dynamicList) {
return dynamicList.map((dynamic order) {
return Order(
id: order['id'],
productName: order['productName'],
productDescription: order['productDescription'],
soldPrice: order['soldPrice'],
quantity: order['quantity'],
createdAt: order['createdAt'],
);
}).toList();
}
void main() {
// Suppose we have a list of dynamic objects representing orders
List<dynamic> dynamicOrders = [
{
'id': 1,
'productName': 'Product 1',
'productDescription': 'Description 1',
'soldPrice': 10.0,
'quantity': 2,
'createdAt': DateTime.now(),
},
{
'id': 2,
'productName': 'Product 2',
'productDescription': 'Description 2',
'soldPrice': 15.0,
'quantity': 1,
'createdAt': DateTime.now(),
},
];
// We can now use our reusable function to convert the dynamic list to an Order list
List<Order> orders = convertDynamicListToOrderList(dynamicOrders);
}