How to use attributes of a subclass of an abstract class?

0

I have the following scenario: an abstract class "ListItem" and the "HeadingItem" and "Contact" classes.

The relationship between them is as follows:

...
}
    abstract class ListItem{

    }

    class HeadingItem implements ListItem{
      String heading;
      HeadingItem(this.heading);
    }

    class Contact implements ListItem{

      Contact(this.id,this.name,this.email,this.phone);

      String id;
      String name;
      String email;
      String phone;

    }

I have created the following scenario, where I create a List<ListItem> mixedList containing objects of type "Contact" and type "HeadingItem":

void funcao(){
...

    List<ListItem> mixedList;
        mixedList.add(Contact("1","nome1","email1","phone1"));
        mixedList.add(Contact("2","nome2","email2","phone2"));
        mixedList.add(Contact("3","nome3","email3","phone3"));
        mixedList.add(HeadingItem("testeHeading"));
...
}

In possession of this List<ListItem> mixedList , I execute the following iteration:

void funcao(){
...
    for(int i = 0 ; i < mixedList.length ; i++){
          if(mixedList[i] is Contact){
            print(mixedList[i].name);
          }
        }
...
}

The compiler neither compiles, stating "The getter 'name'isn't defined for the class ListItem".

From my point of view this should not happen, since there is a code from the flutter docs itself that creates a similar scenario.

Given this result, I attempted a casting, where the compiler no longer acknowledges error in mixedList[i].name but in the debug window it does not even appear any print:

void funcao(){
    ...
        for(int i = 0 ; i < mixedList.length ; i++){
              if(mixedList[i] is Contact){
                print((mixedList[i] as Contact).name);
              }
            }
    ...
    }

Given all this, I ask how do I use mixedList[i].name ?

    
asked by anonymous 09.11.2018 / 23:39

1 answer

0

Assign the value of mixedList[i] to a variable before if , as

final item = mixedList[i];

The item will have type as dynamic , and will be set at runtime.

    
22.11.2018 / 19:27