You can add a drop shadow to a widget in Flutter primarily using the BoxDecoration
class within the decoration
property of a Container
. This allows you to control various aspects of the shadow's appearance.
Implementing Drop Shadows with BoxDecoration
Here's a breakdown of how to add a drop shadow and the key properties involved:
Container(
decoration: BoxDecoration(
color: Colors.white, // Optional: Background color of the container
borderRadius: BorderRadius.circular(8), // Optional: Rounded corners
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5), // Shadow color
spreadRadius: 5, // Spread radius
blurRadius: 7, // Blur radius
offset: Offset(0, 3), // Offset in x, y directions
),
],
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text('Widget with Drop Shadow'),
),
)
Key Properties Explained:
color
(withinBoxShadow
): Defines the color of the shadow. UseColors.grey.withOpacity(0.5)
or any other color with desired transparency for a subtle effect.spreadRadius
: Determines how far the shadow expands from the box before the blur is applied. A positive value increases the size, while a negative value shrinks it.blurRadius
: Controls the amount of blur applied to the shadow. Higher values create a softer, more diffused shadow.offset
: Specifies the position of the shadow relative to the box.Offset(0, 3)
shifts the shadow 0 units horizontally and 3 units vertically downwards. This creates the illusion of the widget floating above the background.
Other Considerations
borderRadius
: Applying rounded corners to theBoxDecoration
enhances the visual appeal of the shadow by making it flow more naturally around the shape.blurStyle
: (Advanced) This property (part ofBoxShadow
) allows you to control the blurring algorithm. It takes aBlurStyle
enum with values likeNormal
,Solid
,Outer
, andInner
. The default isBlurStyle.normal
. The reference mentions it but it's often not necessary to change this for basic drop shadows.- Performance: Complex shadows, especially with high blur and spread radii, can impact performance, particularly on lower-end devices. Be mindful of the shadow's complexity and test thoroughly.
Example with Multiple Shadows
You can also apply multiple shadows to create more complex effects:
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
spreadRadius: 1,
blurRadius: 5,
offset: Offset(0, 2),
),
BoxShadow(
color: Colors.black.withOpacity(0.1),
spreadRadius: 0,
blurRadius: 8,
offset: Offset(0, 5),
),
],
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text('Widget with Multiple Shadows'),
),
)
This creates a layered shadow effect.