How can I add a border to a widget in Flutter?
You can add the Text
as a child
to a Container
that has a BoxDecoration
with border
property:
Container( margin: const EdgeInsets.all(15.0), padding: const EdgeInsets.all(3.0), decoration: BoxDecoration( border: Border.all(color: Colors.blueAccent) ), child: Text('My Awesome Border'),)
Here is an expanded answer. A DecoratedBox
is what you need to add a border, but I am using a Container
for the convenience of adding margin and padding.
Here is the general setup.
Widget myWidget() { return Container( margin: const EdgeInsets.all(30.0), padding: const EdgeInsets.all(10.0), decoration: myBoxDecoration(), // <--- BoxDecoration here child: Text( "text", style: TextStyle(fontSize: 30.0), ), );}
where the BoxDecoration
is
BoxDecoration myBoxDecoration() { return BoxDecoration( border: Border.all(), );}
Border width
These have a border width of 1
, 3
, and 10
respectively.
BoxDecoration myBoxDecoration() { return BoxDecoration( border: Border.all( width: 1, // <--- border width here ), );}
Border color
These have a border color of
Colors.red
Colors.blue
Colors.green
Code
BoxDecoration myBoxDecoration() { return BoxDecoration( border: Border.all( color: Colors.red, // <--- border color width: 5.0, ), );}
Border side
These have a border side of
- left (3.0), top (3.0)
- bottom (13.0)
- left (blue[100], 15.0), top (blue[300], 10.0), right (blue[500], 5.0), bottom (blue[800], 3.0)
Code
BoxDecoration myBoxDecoration() { return BoxDecoration( border: Border( left: BorderSide( // <--- left side color: Colors.black, width: 3.0, ), top: BorderSide( // <--- top side color: Colors.black, width: 3.0, ), ), );}
Border radius
These have border radii of 5
, 10
, and 30
respectively.
BoxDecoration myBoxDecoration() { return BoxDecoration( border: Border.all( width: 3.0 ), borderRadius: BorderRadius.all( Radius.circular(5.0) // <--- border radius here ), );}
Going on
DecoratedBox
/BoxDecoration
are very flexible. Read Flutter — BoxDecoration Cheat Sheet for many more ideas.
The best way is using BoxDecoration()
Advantage
- You can set the border of a widget
- You can set the border Color or Width
- You can set a Rounded corner of a border
- You can add a Shadow of a widget
Disadvantage
BoxDecoration
only use withContainer
widget, so you want to wrap your widget inContainer()
Example
Container( margin: EdgeInsets.all(10), padding: EdgeInsets.all(10), alignment: Alignment.center, decoration: BoxDecoration( color: Colors.orange, border: Border.all( color: Colors.pink[800], // Set border color width: 3.0), // Set border width borderRadius: BorderRadius.all( Radius.circular(10.0)), // Set rounded corner radius boxShadow: [BoxShadow(blurRadius: 10,color: Colors.black,offset: Offset(1,3))] // Make rounded corner of border ), child: Text("My demo styling"), )