user27
user27

Reputation: 41

Flutter Text overlay on Card

I am trying to overlay a title on images in Card widget. I am trying to achieve this using Stack widget, it seems to be messing with my constraints. My original widget:

enter image description here

When I add Stack:

enter image description here

As you can see, the text appears but it destroys the layouts. Any idea to why is this happening? to my knowledge Stack is not supposed to affect any constraints(?), it should be floating on top of the existing widget.

My code:

 return Card(
  clipBehavior: Clip.antiAlias,
  elevation: 3,
  shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(kDefaultPadding / 2)),
  child: Stack(
    children: [
      ClipRRect(
        borderRadius: BorderRadius.circular(kDefaultPadding / 2),
        child: FittedBox(
          fit: BoxFit.cover,
          child: Image.network(widget.data.imageUrl),
        ),
      ),
      Text("Test")
    ],
  ),
);

Upvotes: 1

Views: 1341

Answers (1)

Mobina
Mobina

Reputation: 7119

Add fit: StackFit.expand to the Stack:

Card(
  clipBehavior: Clip.antiAlias,
  elevation: 3,
  shape:
  RoundedRectangleBorder(borderRadius: BorderRadius.circular(kDefaultPadding / 2)),),
  child: Stack(
    fit: StackFit.expand, // this is new
    children: [
      ClipRRect(
...

Note: Instead of Stack you can use a Container with the image set as its decoration image and the text set as its child:

Card(
  clipBehavior: Clip.antiAlias,
  elevation: 3,
  shape:
  RoundedRectangleBorder(borderRadius: BorderRadius.circular(kDefaultPadding / 2)),),
  child: Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        fit: BoxFit.cover,
        image: NetworkImage(widget.data.imageUrl),
      ),
    ),
    child: Center(child: Text("Test"))),
  ),
...

Upvotes: 2

Related Questions