How to add a gradient to a card in Flutter?

Viewed 369

I'm trying to achieve this design:

enter image description here

I also want to use a Card widget provided by Flutter. It comes with some nice theming support that I'd like to use (CardTheme).

So don't know how to give a LinearGradient to a Card. Here's what I tried to do with combining a Card with Container:

Card(
    child: Container(
      margin: EdgeInsets.all(5),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            cardBorderColor,
            Theme.of(context).colorScheme.surface,
          ],
          stops: [0, 0.8],
        ),
      ),
      child: ...

enter image description here

As you can see, the border radius of the card is respected when positioning the Container.

3 Answers

Setting the clipBehavior property of the Card to Clip.antiAlias achieves the desired outcome:

Card(
    clipBehavior: Clip.antiAlias, // <-- this did the trick
    margin: EdgeInsets.all(5),
    child: Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            cardBorderColor,
            Theme.of(context).colorScheme.surface,
          ],
          stops: [0, 0.8],
        ),
      ),
      child: ...

use DecoratedBox instead of Container

You can use borderRadius: BorderRadius.circular(x), there, and wrap everything with ClipRRect for Card color. You may have good reason to have Card and I don't know that, but you check Material widget and with it will be simple to archive, like not to handling extra border/override color of by Card.

Result
enter image description here

Widget


class DX extends StatelessWidget {
  const DX({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.deepPurple,
      body: Center(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(35), //* you can  increase it
          child: Card(
            color: Colors
                .transparent, //* or set the bg Color and remove [ClipRRect]
            child: Container(
              width: 400,
              height: 100,
              // margin: EdgeInsets.all(5),

              decoration: BoxDecoration(
               border: Border.all(width: 0, color: Colors.transparent),
                borderRadius: BorderRadius.circular(22),
                gradient: LinearGradient(
                  colors: [
                    Colors.red,
                    // cardBorderColor,
                    Theme.of(context).colorScheme.surface,
                  ],
                  stops: [0, 0.8],
                ),
              ),
              child: Center(child: Text("asdasd")),
            ),
          ),
        ),
      ),
    );
  }
}

Related