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

Asked

Viewed 96 times

0

I have the following scenario: an abstract class "Listitem" and the classes "Headingitem" and "Contact".

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 set up the following scenario, where I create a List<ListItem> mixedList containing "Contact" and "Headingitem" objects":

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"));
...
}

Possession of that List<ListItem> mixedList , run 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".

Under my point of view this should not occur, since there is code of the very flutter Docs that creates similar scenario. See https://flutter.io/docs/cookbook/lists/mixed-list

Given this result, I tried to make a casting, where the compiler stops accusing error in mixedList[i].name but in the debug window even any print appears:

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

Faced with all this, I ask how do I use the mixedList[i].name?

  • 2

    This is very wrong. But at least your question has served me well. I will never go near this Flutter guy :)

1 answer

0

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

final item = mixedList[i];

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.