Adding borders to containers in Flutter enhances the UI by clearly defining component boundaries and improving visual hierarchy. This article demonstrates two practical approaches to apply borders using the Container widget and BoxDecoration.
Example 1: Basic Border on All Sides
A simple rectangular container with equal borders on all four sides can be achieved using the Border.all constructor. This method is straightforward for cases where uniform border styling is required.
Container(
width: 200,
height: 200,
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: Colors.white,
),
),
)
Dart
In this example, a 2-pixel wide white border is applied equally around a 200×200 container.
Example 2: Custom Border on Specific Sides
For more customization, the Border class allows specification of borders on individual sides. This provides flexibility when a design requires asymmetrical or partial borders.
Container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(12),
border: Border(
left: BorderSide(width: 2, color: Colors.white),
bottom: BorderSide(width: 2, color: Colors.white),
),
),
)
Dart
This container features rounded corners, a green background, and borders only on the left and bottom sides, creating a visually distinctive element.
Code:
import 'package:flutter/material.dart';
class BorderContainer extends StatefulWidget {
const BorderContainer({super.key});
@override
State<BorderContainer> createState() => _BorderContainerState();
}
class _BorderContainerState extends State<BorderContainer> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 200,
height: 200,
decoration: BoxDecoration(
border: Border.all(width: 2, color: Colors.white),
),
),
SizedBox(height: 10),
Container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(12),
border: Border(
bottom: BorderSide(width: 2, color: Colors.white),
left: BorderSide(width: 2, color: Colors.white),
),
),
),
],
),
),
);
}
}
Dart
Output:

Conclusion:
Borders in Flutter can be easily customized using the BoxDecoration class in combination with the Container widget. Whether applying uniform styling or creating unique visual designs with specific side borders, these techniques offer flexibility for crafting polished user interfaces.