Search code examples
flutterflutter-layoutflame

How do I make a child widget expand to fill a parent container inside of a stack when the child has no parameters to alter its layout?


I'm building a card game and using flame to pull the cards from a sprite sheet. The problem is that I set the width and height of the Container that holds the SpriteWidget, but the SpriteWidget expands to either the width or the height of the container, but not both. I want it to expand/stretch to be the same size as the parent container. Unfortunately, the SpriteWidget really has no parameters that could be used to change its size.

I've spent several hours scouring the internet for a solution and tried a number of widgets including FittedBox, Flex, Positioned.fill, etc., but I'm unable to achieve the desired effect. How can I make the SpriteWidget stretch to fill its parent when it has no parameters to do so?

class _PlayerHandPortraitLayout
    extends WidgetView<PlayerHand, _PlayerHandController> {
  @override
  final state;

  const _PlayerHandPortraitLayout(this.state) : super(state);

  @override
  Widget build(BuildContext build) {
    return Stack(
      children: state.displayHand().asMap().entries.map((cardItem) {
        var index = cardItem.key;
        var card = cardItem.value;
        return Positioned(
          left: index * CARD_OVERLAP_OFFSET,
          child: Draggable<Container>(
            childWhenDragging: Container(),
            child: Container(
              color: Colors.purple,
              width: state.cardWidth,
              height: state.cardHeight,
              child: SpriteWidget(
                sprite: state.spriteImages[card.suite.index][card.value.index],
              ),
            ),
            feedback: Container(
              color: Colors.yellow,
              width: state.cardWidth,
              height: state.cardHeight,
              child: SpriteWidget(
                sprite: state.spriteImages[card.suite.index][card.value.index],
              ),
            ),
          ),
        );
      }).toList(),
    );
  }
}

Solution

  • actually this will be not possible, SpriteWidget is designed to expand as long as it fits on the smallest dimension available on its parent, you can check on it source code here.

    This is done so the Sprite will not get distorted when its parent has a different aspect ratio than the ratio of the Sprite.

    If you have an use case where you would want the Sprite to get intentionally distorted, please open an issue on the Flame repository explaining the case, and we can try to take a look on it.