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?
CodePudding user response:
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.