Flutter BoxShadow 组件的使用详解

54 min read

BoxShadow 组件是 Flutter 中用来创建阴影效果的组件。在 Flutter 中,我们可以使用 BoxShadow 来实现各种阴影效果,如立体效果、边框阴影等。本篇文章将详细介绍 BoxShadow 组件的使用方法及其参数。

BoxShadow 的基本参数

在创建 BoxShadow 组件时,我们需要指定下列几个基本参数。

  • color:指定阴影的颜色。
  • offset:指定阴影的偏移量。
  • blurRadius:指定阴影的模糊半径。
  • spreadRadius:指定阴影的扩散半径。

代码示例:

BoxShadow(
  color: Colors.grey.withOpacity(0.5),
  offset: Offset(0.5, 0.5),
  blurRadius: 5,
  spreadRadius: 2,
)

BoxShadow 的应用场景

  • 立体效果:通过为一个 Container 组件添加 BoxShadow,实现立体效果。

代码示例:

Container(
  height: 100,
  width: 100,
  decoration: BoxDecoration(
    color: Colors.white,
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.5),
        offset: Offset(0.5, 0.5),
        blurRadius: 5,
        spreadRadius: 2,
      )
    ],
  ),
)
  • 边框阴影:将 BoxShadow 的偏移量设为负数,使阴影出现在边框外部,可以实现边框阴影效果。

代码示例:

Container(
  height: 100,
  width: 100,
  decoration: BoxDecoration(
    color: Colors.white,
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.5),
        offset: Offset(-0.5, -0.5),
        blurRadius: 5,
        spreadRadius: 2,
      )
    ],
    border: Border.all(
      color: Colors.grey.withOpacity(0.5),
      width: 1,
    ),
  ),
)
  • 投影效果:通过将 BoxShadow 的颜色设为透明,实现投影效果。

代码示例:

Container(
  height: 100,
  width: 100,
  decoration: BoxDecoration(
    color: Colors.white,
    boxShadow: [
      BoxShadow(
        color: Colors.transparent,
        offset: Offset(0, 5),
        blurRadius: 5,
        spreadRadius: 0,
      ),
    ],
  ),
)

BoxShadow 的高级用法

BoxShadow 还有一些高级用法,可以通过下列参数来实现。

  • borderRadius:指定阴影边界的圆角半径。

代码示例:

Container(
  height: 100,
  width: 100,
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(10),
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.5),
        offset: Offset(0.5, 0.5),
        blurRadius: 5,
        spreadRadius: 2,
      )
    ],
  ),
)
  • gradient:指定阴影的填充样式。

代码示例:

Container(
  height: 100,
  width: 100,
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(10),
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.5),
        offset: Offset(0.5, 0.5),
        blurRadius: 5,
        spreadRadius: 2,
        gradient: LinearGradient(
          colors: [
            Colors.red,
            Colors.orange,
            Colors.yellow,
          ],
        ),
      ),
    ],
  ),
)
  • shape:指定阴影的形状,如圆形、矩形、椭圆形等。

代码示例:

Container(
  height: 100,
  width: 100,
  decoration: BoxDecoration(
    color: Colors.white,
    shape: BoxShape.circle,
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.5),
        offset: Offset(0.5, 0.5),
        blurRadius: 5,
        spreadRadius: 2,
      )
    ],
  ),
)

以上就是 BoxShadow 组件的使用方法及其参数的详细介绍。BoxShadow 是实现阴影效果的核心组件之一,在开发过程中应该熟练掌握。