flutter - How to make a raised button that has a gradient background?

后端 未结 10 1671
野性不改
野性不改 2021-01-31 14:52

Is there a way to change the raised button background color to a gradient? if not, how can I achieve something like this?

10条回答
  •  梦如初夏
    2021-01-31 15:50

    You can create a custom one yourself

    class RaisedGradientButton extends StatelessWidget {
      final Widget child;
      final Gradient gradient;
      final double width;
      final double height;
      final Function onPressed;
    
      const RaisedGradientButton({
        Key key,
        @required this.child,
        this.gradient,
        this.width = double.infinity,
        this.height = 50.0,
        this.onPressed,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Container(
          width: width,
          height: 50.0,
          decoration: BoxDecoration(gradient: gradient, boxShadow: [
            BoxShadow(
              color: Colors.grey[500],
              offset: Offset(0.0, 1.5),
              blurRadius: 1.5,
            ),
          ]),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
                onTap: onPressed,
                child: Center(
                  child: child,
                )),
          ),
        );
      }
    }
    

    And use it anywhere as follows:

    RaisedGradientButton(
      child: Text(
        'Button',
        style: TextStyle(color: Colors.white),
      ),
      gradient: LinearGradient(
        colors: [Colors.green, Colors.black],
      ),
      onPressed: (){
        print('button clicked');
      }
    ),
    

    You can further play around with the shadow and rounded borders by editing the Container's decoration property until it matches your spec.

提交回复
热议问题