How to get an access to a property of an inheriting class

Viewed 19

I have one main class and three classes that inherits from it.

class Product {
      const Product(this.price);
    
      final int price;
    }
    
    class Book extends Product {
      const Book(this.genre, super.price);
    
      final String genre;
    }
    
    class CD extends Product {
      const CD(this.genre, super.price);
    
      final String genre;
    }
    
    class Sticker extends Product {
      const Sticker(this.color, super.price);
    
      final Color color;
    }

And then I have widget that needs either Book or CD. Both have genre property. But I don't have access to it because the main class has only price property.

class BookOrCD extends StatelessWidget {
  const BookOrCD(this.product,{Key? key}) : super(key: key);

  final Product product;

  @override
  Widget build(BuildContext context) => Text(product.genre);
}

I can't add genre to Product class because Sticker doesn't need it. And I can't specify if Product is Book or CD because it can be either of them. I know there are lots of workarounds to that problem, but I'm looking for some clean solution. Maybe some generic function as helper for example.

1 Answers

You can check if the current instance is of a specific type like so:

  if (product is Book) {
       product.genre
    }

If you want to include the logic inside your widgets you can do like this for example:

 Text((product is Book) ? product.genre : '') 
Related