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

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.



Solution 1:[1]

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 : '') 

Solution 2:[2]

You can initialize a creation_time variable right before your element appears on the screen, and then a destory_time variable right after your element gets destoryed.

from datetime import datetime

# REST OF THE CODE

creation_time = datetime.now()

# ......

destroy_time = datetime.now()

appearance_time = destory_time - creation_time

Solution 3:[3]

This may have been your thought but I'd try using EC.visibility_of_element_located in a while loop. When the element is first located, store the time in a variable as the above answer suggests. Then when the element is no longer visible, store the time in another variable and stop the loop

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Eberl
Solution 2
Solution 3 Callum