How to add LinearGradient colour to "cupertino_rounded_corners" widget?

Issue

I have created a Squircle widget using the documentation for "cupertino_rounded_corners" at this link: https://pub.dev/packages/cupertino_rounded_corners with the below code.

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.all(
          Radius.circular(4.0),
        ),
      ),
      margin: EdgeInsets.all(20.0),
      child: Material(
        color: Colors.pink,
        shape: SquircleBorder(
          radius: BorderRadius.all(
            Radius.elliptical(40.0, 40.0),
          ),
        ),
        elevation: 8.0,
        child: Padding(
            padding: EdgeInsets.all(30.0), child: Text("This is an example.")),
      ),
    );
  }

The widget looks like this:

Squircle

However, I am unable to add a LinearGradient for this widget.

I changed the child of Material to include a LinearGradient, but it changes the colour of the entire rectangle (does not have rounded corners anymore!).

child: Container(
  decoration: BoxDecoration(
    gradient: LinearGradient(
      begin: Alignment.centerLeft,
      end: Alignment.centerRight,
      colors: [Colors.purple, Colors.blue],
    ),
  ),
          
  child: Padding(
    padding: EdgeInsets.all(30.0),
    child: Text("This is an example."),
  ),
),

Results in below:

Wrong Squircle with Gradient

Question: How to add a LinearGradient for this widget?

Solution

I rearranged some of the code and got it to work with the following:

Material(
  color: Colors.transparent,
  shape: const SquircleBorder(
    radius: BorderRadius.all(
      Radius.elliptical(40.0, 40.0),
    ),
  ),
  clipBehavior: Clip.antiAlias,
  elevation: 8.0,
  child: Container(
    padding: const EdgeInsets.all(30.0),
    decoration: const BoxDecoration(
      gradient: LinearGradient(
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
        colors: [Colors.purple, Colors.blue],
      ),
    ),
    child: const Text("This is an example."),
  ),
),

The important part is that your Material Widget has clipBehavior: Clip.antiAlias

Answered By – Will Hlas

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.