Custom Clipper

CustomClipper is the base class for clipping in Flutter and it’s used by a four widgets: ClipRect , ClipRRect , ClipOval , ClipPath .

Each of these has a defined behavior; so if you wrap a Red Container in a ClipOval , the result is a rounded circle:

Change the height or the width of the Container and it becomes an Oval. Consider for a moment how fast and easy it is to tune such an oval in Flutter; all you have to do is change the height and/or width and hit Ctrl+\ for Hot Reload to see how your changes look in less than a second. A little bigger, a little wider, no maybe little smaller…

Now what if you want to customize the size and location of the clip? that’s what the CustomClipper made for. Let’s create one for our ClipOval Widget

class CustomRect extends CustomClipper<Rect>{

@override

Rect getClip(Size size) {

// TODO: implement getClip

}

@override

bool shouldReclip(CustomRect oldClipper) {

// TODO: implement shouldReclip

}

}

NOTE : It’s very important to be specific about the generic type in class inheritance part you can see what your widget require from the clipper property. Rect in this example.

When you inherit from the CustomClipper class you need to override two methods.

The first is getClip(). This provides you with size of the RenderBox being clipped and requires you to return a Rect . This Rect will define the size and location of the clip . (FYI: Every visible Widget has a RenderBox .)

So if we return this :

Rect getClip(Size size) {

Rect rect = Rect.fromLTRB(0.0, 0.0, size.width, size.height);

return rect;

}

Code note : using the fromLTRB constructor we must provide the Left, Top, Right, Bottom points

This will change nothing because the Rect here is the same as the widget’s bounding box.

But what if you want to show only half of the oval? We can do that easily by changing the Left point of the rectangle to -size.width and if you want to see the other half just change the right point to size.width*2 .

The other method you’re going to need to override is shouldReclip(). This method will be called whenever you provide a new object (in this case CustomClipper<Rect> ) is created to compare it with the old one and when it return true getClip will get called and it’s not vise-versa because the getClip method can also be triggered when the size of the box changes.