flutterbuttonlinear-gradients

how to create a gradient color in elevated button in flutter?


I trying to create a gradient button in flutter but in ElevatedButton shows some shadow or its strucuture there even when the color was set to transparent.

Here I have used DecoratedBox for applying gradient color is there any way to apply gradient in ElevatedButton?

The Code I have used

               child: DecoratedBox(
                  decoration: BoxDecoration(
                      gradient: LinearGradient(
                    colors: [
                      Colors.red,
                      Colors.blue,
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  )),
                  child: ElevatedButton(
                      onPressed: () {
                        // Navigator.of(context).push(MaterialPageRoute(
                        //     builder: (BuildContext context) => RegisterScreen()));
                      },
                      style: ElevatedButton.styleFrom(
                          primary: Colors.transparent,
                          onPrimary: Colors.transparent),
                      child: Text(
                        "Register",
                        style: TextManager.btnText,
                      )),
                ),

by setting elevation to 0 resolved but when I click the button the thing is also visible. Setting splash color to transparent also didn't work.

The output button is here

enter image description here


Solution

  • You can simply wrap your child property with an Ink widget. By doing so you will be able to apply a gradient and keep the elevated effect from the button.

    Code Sample

    class MyWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return ElevatedButton(
          style: ElevatedButton.styleFrom(
            padding: const EdgeInsets.all(0.0),
            elevation: 5,
          ),
          onPressed: () {},
          child: Ink(
            decoration: BoxDecoration(
              gradient: LinearGradient(colors: [Colors.blue, Colors.cyan]),
            ),
            child: Container(
              padding: const EdgeInsets.all(10),
              constraints: const BoxConstraints(minWidth: 88.0),
              child: const Text('OK', textAlign: TextAlign.center),
            ),
          ),
        );
      }
    }
    

    Screenshot

    enter image description here

    Try the full test code on DartPad