Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter/Dart: reaction of ui depending on the inheritance class of an object

I have a class for menu-entries:

abstract class MenuSelection {
  MenuSelection({required this.label});

  final String label;
}

and two classes that inherit from this class:

///for menu entries with an image
abstract class ImageSelection extends MenuSelection {
  ImageSelection({required this.image, required super.label});

  final String image;
}


///for menu entries with an icon
abstract class IconSelection extends MenuSelection {
  IconSelection({required this.iconData, required super.label});

  final IconData iconData;
}

I want to have one DropDownMenu and react depending on the given class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class _DropDownMenuItem extends StatelessWidget {
  const _DropDownMenuItem({super.key, required this.selection});
  final MenuSelection selection;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        if (selection is ImageSelection)
          Image.asset(
            selection.image,
            width: 30,
          )
        else if (selection is IconSelection)
          Icon(
            selection.iconData,
            size: 30,
          )
        else
          Container(),
        const SizedBox(
          width: 10,
        ),
        Text(selection.label.tr()),
      ],
    );
  }
}

I thought it must work that way because it works for example when used with Bloc and getting the current type of state…
Actually AndroidStudio tells me that class MenuSelection has no image or icon property instead of recognizing that this is ImageSelection or IconSelection.

Can someone explain this behavior?

>Solution :

The implicit type promotion only works for local variables, not for class fields. You can read this answer if you need a detailed explanation and a possible solution.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading