¿Cómo puedo agregar sombra al widget en Flutter?

104

¿Cómo puedo agregar sombra al widget como en la imagen de abajo?

Este es mi código de widget actual.

Imagen con sombra

Mohammed Mustafa
fuente
echa un vistazo
Raouf Rahiche
puede usar la pila
Akshay Paliwal

Respuestas:

240

Echa un vistazo a BoxShadow y BoxDecoration

A Containerpuede tomar un BoxDecoration(saliendo del código que había publicado originalmente) que toma unboxShadow

return Container(
  margin: EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
  height: double.infinity,
  width: double.infinity,
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.only(
      topLeft: Radius.circular(10),
        topRight: Radius.circular(10),
        bottomLeft: Radius.circular(10),
        bottomRight: Radius.circular(10)
    ),
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.5),
        spreadRadius: 5,
        blurRadius: 7,
        offset: Offset(0, 3), // changes position of shadow
      ),
    ],
  ),
)

Captura de pantalla

ingrese la descripción de la imagen aquí

Ashton Thomas
fuente
1
todo es mejor que solo
shinriyo
1
Gran respuesta: ¡tnx! ¿Cómo tendrías el efecto dominó sobre el botón? actualmente está ondeando debajo del botón.
Nitzanwe
1
Es mejor usarlo borderRadius: BorderRadius.circular(10.0)si todos los bordes son iguales.
Vinoth Vino
51

Usar BoxDecorationcon BoxShadow.

Aquí hay una demostración visual que manipula las siguientes opciones:

  • opacidad
  • x desplazamiento
  • y offset
  • radio de desenfoque
  • radio de propagación

El gif animado no funciona tan bien con los colores. Puede probarlo usted mismo en un dispositivo.

ingrese la descripción de la imagen aquí

Aquí está el código completo para esa demostración:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ShadowDemo(),
      ),
    );
  }
}

class ShadowDemo extends StatefulWidget {
  @override
  _ShadowDemoState createState() => _ShadowDemoState();
}

class _ShadowDemoState extends State<ShadowDemo> {
  var _image = NetworkImage('https://placebear.com/300/300');

  var _opacity = 1.0;
  var _xOffset = 0.0;
  var _yOffset = 0.0;
  var _blurRadius = 0.0;
  var _spreadRadius = 0.0;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Center(
          child:
          Container(
            decoration: BoxDecoration(
              color: Color(0xFF0099EE),
              boxShadow: [
                BoxShadow(
                  color: Color.fromRGBO(0, 0, 0, _opacity),
                  offset: Offset(_xOffset, _yOffset),
                  blurRadius: _blurRadius,
                  spreadRadius: _spreadRadius,
                )
              ],
            ),
            child: Image(image:_image, width: 100, height: 100,),
          ),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Padding(
            padding: const EdgeInsets.only(bottom: 80.0),
            child: Column(
              children: <Widget>[
                Spacer(),
                Slider(
                  value: _opacity,
                  min: 0.0,
                  max: 1.0,
                  onChanged: (newValue) =>
                  {
                    setState(() => _opacity = newValue)
                  },
                ),
                Slider(
                  value: _xOffset,
                  min: -100,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _xOffset = newValue)
                  },
                ),
                Slider(
                  value: _yOffset,
                  min: -100,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _yOffset = newValue)
                  },
                ),
                Slider(
                  value: _blurRadius,
                  min: 0,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _blurRadius = newValue)
                  },
                ),
                Slider(
                  value: _spreadRadius,
                  min: 0,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _spreadRadius = newValue)
                  },
                ),
              ],
            ),
          ),
        )
      ],
    );
  }
}
Suragch
fuente
16

Captura de pantalla:

ingrese la descripción de la imagen aquí


Container(
  decoration: BoxDecoration(
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.8),
        spreadRadius: 10,
        blurRadius: 5,
        offset: Offset(0, 7), // changes position of shadow
      ),
    ],
  ),
  child: Image.asset(chocolateImage),
)
CopsOnRoad
fuente
9

Use Material con shadowColor dentro del contenedor de esta manera:

Container(
  decoration: BoxDecoration(
      borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(10),
          bottomRight: Radius.circular(10)),
      boxShadow: [
        BoxShadow(
            color: Color(0xffA22447).withOpacity(.05),
            offset: Offset(0, 0),
            blurRadius: 20,
            spreadRadius: 3)
      ]),
  child: Material(
    borderRadius: BorderRadius.only(
        bottomLeft: Radius.circular(10),
        bottomRight: Radius.circular(10)),
    elevation: 5,
    shadowColor: Color(0xffA22447).withOpacity(.05),
    color: Color(0xFFF7F7F7),
    child: SizedBox(
      height: MediaQuery.of(context).size.height / 3,
    ),
  ),
)
Yasmin Ali
fuente
6

así es como lo hice

    Container(
  decoration: new BoxDecoration(
    boxShadow: [
      BoxShadow(
        color: Colors.grey[200],
        blurRadius: 2.0, // has the effect of softening the shadow
        spreadRadius: 2.0, // has the effect of extending the shadow
        offset: Offset(
          5.0, // horizontal, move right 10
          5.0, // vertical, move down 10
        ),
      )
    ],
  ),
  child: Container( 
       color: Colors.white, //in your example it's blue, pink etc..
       child: //your content
  )
Amera Abdallah
fuente
3

Las respuestas dadas hacen el truco para la sombra externa, es decir, alrededor del widget. Quería una sombra en el widget que está dentro de los límites y, de acuerdo con el problema de github, todavía no hay ningún atributo insertado en ShadowBox. Mi solución fue agregar una capa de widget con un degradado usando el widget de pila para que parezca que el widget tiene las sombras. Debe utilizar mediaQuery para las dimensiones, de lo contrario, el diseño se estropeará en diferentes dispositivos. Aquí hay una muestra de código para una mejor comprensión:

Stack(
            children: <Widget>[
              Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    fit: BoxFit.cover,
                    image: AssetImage("assets/sampleFaces/makeup.jpeg"),
                    // fit: BoxFit.cover,
                  ),
                ),
                height: 350.0,
              ),
              Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: FractionalOffset.topCenter,
                    end: FractionalOffset.bottomCenter,
                    colors: [
                      Colors.black.withOpacity(0.0),
                      Colors.black54,
                    ],
                    stops: [0.95, 5.0],
                  ),
                ),
              )
            ],
          ),
Yudhishthir Singh
fuente
0
class ShadowContainer extends StatelessWidget {
  ShadowContainer({
    Key key,
    this.margin = const EdgeInsets.fromLTRB(0, 10, 0, 8),
    this.padding = const EdgeInsets.symmetric(horizontal: 8),
    this.circular = 4,
    this.shadowColor = const Color.fromARGB(
        128, 158, 158, 158), //Colors.grey.withOpacity(0.5),
    this.backgroundColor = Colors.white,
    this.spreadRadius = 1,
    this.blurRadius = 3,
    this.offset = const Offset(0, 1),
    @required this.child,
  }) : super(key: key);

  final Widget child;
  final EdgeInsetsGeometry margin;
  final EdgeInsetsGeometry padding;
  final double circular;
  final Color shadowColor;
  final double spreadRadius;
  final double blurRadius;
  final Offset offset;
  final Color backgroundColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: margin,
      padding: padding,
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(circular),
        boxShadow: [
          BoxShadow(
            color: shadowColor,
            spreadRadius: spreadRadius,
            blurRadius: blurRadius,
            offset: offset,
          ),
        ],
      ),
      child: child,
    );
  }
}
O Thạnh Ldt
fuente
-1

Agregue sombra de caja al contenedor en aleteo

  Container(
      margin: EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
      height: double.infinity,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
            bottomLeft: Radius.circular(10),
            bottomRight: Radius.circular(10)
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.5),
            spreadRadius: 5,
            blurRadius: 7,
            offset: Offset(0, 3), // changes position of shadow
          ),
        ],
      ),
  )

Aquí está mi salida ingrese la descripción de la imagen aquí

Paresh Mangukiya
fuente