0

I have one data type Map<String,CartItem> _items = {}; And using print(_items)

And the output is:

{
  p1: Instance of 'CartItem', 
  p2: Instance of 'CartItem'
}

Is there any method by which I can see the full logs(values) of CartItem? as my expectation is:

{
  p1: some json formatted structure, 
  p2: some json formatted structure
}
class CartItem {
  final String id;
  final String title;

  CartItem({
    @required this.id,
    @required this.title,
  });
}
MendelG
  • 14,885
  • 4
  • 25
  • 52
Arun
  • 57
  • 2
  • 5

2 Answers2

8

You just need to override your toString method:

class CartItem {
  final String id;
  final String title;

  CartItem({
    required this.id,
    required this.title,
  });

  @override
  String toString() {
    return '{id: $id, title: $title}';
  }
}

Usage:

main() async {
  CartItem item = CartItem(id: '1', title: 'title');
  print(item); // {id: 1, title: title}

  Map<String, CartItem> items = {
    'p1': CartItem(id: '1', title: 'title'),
    'p2': CartItem(id: '2', title: 'titl2'),
  };
  print(items); // {p1: {id: 1, title: title}, p2: {id: 2, title: titl2}}


  List<CartItem> list = [
    CartItem(id: '1', title: 'title'),
    CartItem(id: '2', title: 'title2'),
  ];
  print(list); // [{id: 1, title: title}, {id: 2, title: title2}]
}
3

You have to loop through the items to get their specific values and not their instances.

_items.forEach((item) {
  print('id: ${item.id}, title: ${item.title}');
});
MendelG
  • 14,885
  • 4
  • 25
  • 52
J. S.
  • 8,905
  • 2
  • 34
  • 44