i want to a list of string to show in a dropdown, but i am not able to do that. i have a list named categories, i am initializing it with some data, i want to access it something like "categories.CategoryName" or "categories.SubCategories[0]"
i am declaring a list as
List<categoryListModel> categories = [
categoryListModel(
CategoryName: 'Print Design',
SubCategories: [
'Brochers',
'Flyers',
'Posters',
'Business Cards',
'Packaging',
'Stationery'
],
),
categoryListModel(
CategoryName: 'Digital Design',
SubCategories: [
'Web Design',
'App Design',
'Social Media Graphics',
'Email Templates',
'Banner Ads',
'Infographics'
],
),];
and my model is
class categoryListModel {
String CategoryName;
List<String> SubCategories;
categoryListModel({
required this.CategoryName,
required this.SubCategories,
});
}
when i print category
it prints
I/flutter (10525): [Instance of 'categoryListModel', Instance of 'categoryListModel', Instance of 'categoryListModel', Instance of 'categoryListModel', Instance of 'categoryListModel', Instance of 'categoryListModel', Instance of 'categoryListModel', Instance of 'categoryListModel', Instance of 'categoryListModel', Instance of 'categoryListModel']
3
Answers
Instead of
try:
What happened…
Looks like you tried to call
print
like this:In this case
categories
is a list.All classes in dart has default
toString
implementation. Same with List implementations.Which means, that it will print a list of items it contains, calling
toString
for each item.How to fix
In order to customize how
categoryListModel
instances are printed you got to overridetoString
, e.g.:In this case
print(categories)
will emit smth like this:Then if you want to make list to print something different from just list of inner items, then looks like you should either implement your own version of
List
or create a wrapper:In Dart newly created class will be print as Instance of ClassName. If you want to modify the value which is printing, then you have to override the toString() method in the categoryListModel class.
Then if we call
Output: