简体   繁体   中英

Flutter - Hero widget - 2 hero with same key?

Let's say I have a ProductCard() widget and ProductDetails() widget. On my home screen, I want to show deals of the day and deals of the week. When I wrap ProductCard() with Hero() widget, I give product.id as a key. Now there is a problem when the same product comes in both of the categories: deals of the day and deals of the week, as there is a conflict of keys. What is the solution in this case, or Hero() can't be used in such a scenario?

Lets suppose, first screen is MainScreen and Second one is DetailScreen

class MainScreen extends StatelessWidget {
String type = 'weekly/daily chose one';
..rest code...
    child: Hero(
      tag: 'imageHero$type', //assign the key including type weekly or daily etc
      child: .. content widget ...
    ),
    onTap: () {
      Navigator.push(context, MaterialPageRoute(builder: (_) {
        return DetailScreen(type:type); //pass the type as parameter to constructor
      }));
    },
  ...rest code...

On the detail screen consume the type inside the key as

class DetailScreen extends StatelessWidget {
  ... rest code ...
      child: Hero(
        tag: 'imageHero${widget.type}', // user the passed type here as included in the key
        child: ... your widgets ...
      ),
    ),
    onTap: () {
      Navigator.pop(context);
    },
  ... rest code ...

Edit: I assumed that you've already achieved product.id as a key assignment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM