Search code examples
flutterflutter-web

Flutter how to fill gredient color for raised button?


I'm trying to render gradient button but on some device, gradient colors are not expanded like image below.

How can I fix this?
Thanks!

Code

class GradientButton extends StatelessWidget {
  final Widget child;
  final VoidCallback onPressed;
  const GradientButton({@required this.child, @required this.onPressed});
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      textColor: Colors.white,
      shape: StadiumBorder(),
      padding: const EdgeInsets.all(0.0),
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: <Color>[Color(0xff00F260), Color(0xff0575E6)],
          ),
        ),
        padding: EdgeInsets.all(8.0),
        child: child
        onPressed: onPressed,
      ),
    );
  }
}

Solution

  • import 'package:flutter/material.dart';
    import 'package:flutter/widgets.dart';
    
    class GradientButton extends StatelessWidget {
      final Widget child;
      final VoidCallback onPressed;
    
      const GradientButton({Key key, this.onPressed, this.child}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Container(
          decoration: ShapeDecoration(
            shape: const StadiumBorder(),
            gradient: LinearGradient(
              colors: [Color(0xff00F260), Color(0xff0575E6)],
            ),
          ),
          child: MaterialButton(
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            shape: const StadiumBorder(),
            child: child,
            onPressed: onPressed,
          ),
        );
      }
    }
    

    You also get some MaterialButton effects like Ripple on tap, Disabled when onPressed is null, etc. For the elevation set shadows property in ShapeDecoration

    shadows: [
      BoxShadow(
          color: Colors.black54,
          spreadRadius: 0.5,
          blurRadius: 3,
          offset: Offset(1, 1))
    ]