Creating circular elements is a common need in UI design, perfect for user avatars, status indicators, or stylish buttons. While Flutter doesn’t have a specific CircleContainer widget, shaping a standard Container into a circle is incredibly simple.
This guide will show you the right way to do it using BoxDecoration.
The BoxDecoration Method
The key to customizing a Container‘s shape, color, or border lies in its decoration property. By providing a BoxDecoration widget, you can easily make it circular.
The magic happens with one line: shape: BoxShape.circle.
Code Example
Here is a basic example of a circular Container. For the circle to be perfect, ensure the height and width are equal.
import 'package:flutter/material.dart';
class CircleContainer extends StatelessWidget {
const CircleContainer({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Circular Container'),
),
body: Center(
child: Container(
height: 150,
width: 150,
decoration: const BoxDecoration(
color: Colors.blue,
shape: BoxShape.circle,
),
),
),
);
}
}
Dart⚠️ Important Tip: The color Property
A common mistake that trips up new developers is trying to use the Container‘s color property at the same time as its decoration property. This will cause an error.
If you use decoration, the color must be inside the BoxDecoration.
Wrong (throws an error):
// ❌ This will not work!
Container(
color: Colors.red,
decoration: const BoxDecoration(
shape: BoxShape.circle,
),
)
DartRight:
// ✅ Correct way
Container(
decoration: const BoxDecoration(
color: Colors.red, // Color is inside decoration
shape: BoxShape.circle,
),
)
DartAdding Content and Borders
Once you have your circle, you can easily add a child or a border.
Adding a Child (like an Icon or Text)
Use the child property of the Container to place another widget inside the circle. It will be automatically clipped to the circular shape.
Container(
height: 150,
width: 150,
decoration: const BoxDecoration(
color: Colors.blue,
shape: BoxShape.circle,
),
child: const Icon(
Icons.person,
color: Colors.white,
size: 100,
),
)
DartAdding a Border
To add a border around your circle, simply add the border property to your BoxDecoration.
Container(
height: 150,
width: 150,
decoration: BoxDecoration(
color: Colors.grey.shade200,
shape: BoxShape.circle,
border: Border.all(
color: Colors.blue,
width: 4,
),
),
child: const Center(
child: Text(
'Avatar',
style: TextStyle(fontSize: 24),
),
),
)
DartKey Takeaways
- To create a circle, use a
Containerwith equalheightandwidth. - Set the
decorationproperty to aBoxDecorationwithshape: BoxShape.circle. - Remember to place the
colorproperty inside theBoxDecoration, not outside of it.