为Flutter卡片添加自定义阴影框。

38

我已在Flutter应用程序中实现了卡片。我需要为每个卡片设置自定义BoxShadow。如何做到这一点?

目前我尝试的是将BoxShadow属性添加到Card()构造函数中,但这并不起作用...

5个回答

64
Card小部件没有decoration属性,因此您需要在Container中创建一个card,然后将BoxShadow应用于该Container。
class MyCard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container(
      child: new Card(
        child: new Center(
          child: new Icon(
            Icons.refresh,
            size: 150.0,
          ),
        ),
      ),
      decoration: new BoxDecoration(
        boxShadow: [
          new BoxShadow(
            color: Colors.black,
            blurRadius: 20.0,
          ),
        ],
      ),
    );
  }
}

输入图片说明


1
谢谢,我还想要的是标题文本周围的边距,这样副标题和标题之间就有间隔了,你能帮我吗? - Nirav Madariya
2
我不明白你的意思,但如果你想要添加一些边距,你可以很容易地将以下代码添加到容器中: margin: const EdgeInsets.all(10.0) - Raouf Rahiche
我正在使用这个。 - Ajay Kumar

20

只需将卡片放入一个容器中,并获取 boxShadow 属性,即可为卡片小部件应用阴影效果。

new Container(
  width: 100,
  height: 100,
  decoration: new BoxDecoration(
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(.5),
        blurRadius: 20.0, // soften the shadow
        spreadRadius: 0.0, //extend the shadow
        offset: Offset(
          5.0, // Move to right 10  horizontally
          5.0, // Move to bottom 10 Vertically
        ),
      )
    ],
  ),
),

17

查看卡片小部件

      @override
      Widget build(BuildContext context) {
        return Scaffold(
            backgroundColor: Color(0xFFdde0e3),
            body: SingleChildScrollView(
              child: Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Card(
                      elevation:5,
                      margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 16.0),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(0.0),
                      ),
                      child: Container(
                        height: 200,
                      ),
                    )
                  ],
                ),
              ),
            ));
      }

输入图像描述


14

当谈论阴影时,主要可以通过调整模糊度颜色来改变阴影的外观。

因此,您可以在不编写额外代码的情况下执行此操作。

Card(
  elevation: 4,  // Change this 
  shadowColor: Colors.black12,  // Change this 
  child: Center(child: Text('Hey, dude.')),
),

1
只有在不需要偏移和模糊效果的情况下,elevationshadowColor 才能起作用。offsetblurRadius 可以在 BoxShadow 对象中定义,这两个参数无法通过调整来实现。 - tanghao

-2

使用elevation

Card(elevation: 10, child: theWidget),

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接