首页 > 解决方案 > Flutter: generic list handles different key, value pairs

问题描述

I have a class that has a generic List as property, that I have to initialize, and that has a function that returns a card using that list:

class buildCard{
buildCard(this.list);
final List list;

Widget buildCard(int position) {
      return Card(child: ListTile(title: list[position].name,),);
}

Now, as you can see, I use

 list[position].name 

that works for the majority of the stuff that I have, but, in case I will have a list which doesn't have "name" as key, I will have some troubles. How can I avoid this problem?

标签: listdictionaryflutterkey

解决方案


You can use is to check the type

Widget buildCard() {
  if(list[position].name is List) {
    return Card(child: ListTile(title: list[position][0].name,),); // or similar - I don't know your exact structure
  } else { 
    return Card(child: ListTile(title: list[position].name,),);
  }
}

推荐阅读