What is ClipRRect in Flutter: Usage and Examples
ClipRRect in Flutter is a widget that clips its child using a rounded rectangle shape. It is commonly used to create rounded corners on widgets like images or containers by specifying a border radius.How It Works
ClipRRect works by taking a child widget and cutting its edges to fit inside a rounded rectangle shape. Imagine you have a photo printed on a square paper, and you want to trim the corners to make them rounded. ClipRRect does exactly that but digitally for any widget.
This clipping happens before the widget is painted on the screen, so anything outside the rounded rectangle is hidden. You control the roundness by setting the borderRadius property, which defines how curved the corners should be.
Example
This example shows how to use ClipRRect to create an image with rounded corners.
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('ClipRRect Example')), body: Center( child: ClipRRect( borderRadius: BorderRadius.circular(20), child: Image.network( 'https://flutter.dev/assets/homepage/carousel/slide_1-bg-4e2fcef8a8a3f8e6e3a1e2d7a6f9d1a7d1a7a7a7a7a7a7a7a7a7a7a7a7a7a7.png', width: 200, height: 200, fit: BoxFit.cover, ), ), ), ), ); } }
When to Use
Use ClipRRect when you want to give your widgets rounded corners for a softer, more modern look. It is especially useful for images, buttons, cards, or containers where sharp edges might look harsh.
For example, if you have a profile picture or a thumbnail image, clipping it with rounded corners makes the UI friendlier and visually appealing. It also helps when you want to mask parts of a widget that overflow its bounds.
Key Points
ClipRRectclips child widgets to a rounded rectangle shape.- You control corner roundness with the
borderRadiusproperty. - It is useful for styling images, containers, and buttons with smooth corners.
- Clipping happens before painting, so content outside the shape is hidden.
Key Takeaways
ClipRRect clips widgets to rounded rectangles using borderRadius.