0

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:

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?

MCB
  • 503
  • 1
  • 8
  • 21
  • 1
    Why are you using `abstract` classes? Do you have classes extending `ImageSelection` and `IconSelection`? Try to cast the `selection` like `(selection as ImageSelection).image for example. – TripleNine Sep 19 '22 at 16:34
  • Yes, I have some classes extending them :) Thank you,I allready did this... but I want to understand why it don't work in the other way and minimize the risk of an error during runtime – MCB Sep 19 '22 at 16:40

1 Answers1

1

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.

TripleNine
  • 1,457
  • 1
  • 4
  • 15