
Flutter: What are Containers?
Flutter has an interesting way of constructing UI and sees us using a variety of Widgets
to compose a particular view.
In this article, we'll be looking at the Container
widget and how it is used within Flutter.
Using the Container
Let's use the following piece of code as a starting point for our application:
void main() => runApp(new MaterialApp(title: 'Containers', home: new Home()));
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text('Containers')),
body: new Container());
}
}
Application Starting Point
The Container
can be thought of as a widget that allows us to ensure the child
elements have appropriate padding
, constraints
, margin
, and so on.
By default, the Container
will attempt to take up the entire width and height of their parent. If the Container
has child elements, it will resize itself to the size of the children unless otherwise specified.
We can see this in action by giving the Container
a color:
return new Scaffold(
appBar: new AppBar(title: new Text('Containers')),
body: new Container(color: Colors.teal));
Container with Colour
The Container
has taken up the entire size of the screen, as it is the main child of the body
. This will change if we add anotherContainer
like so:
return new Scaffold(
appBar: new AppBar(title: new Text('Containers')),
body: new Container(
height: 200.0,
width: 200.0,
color: Colors.teal,
margin: const EdgeInsets.all(10.0),
child: new Center(child: new Text('Hello World'))
)
);
Double Containers
The Center
and Text
elements are now only taking up space to the height
and width
of the parent and they have 10.0
margin
. This is great for custom widgets and UI that we
So when should you use a Container
? Any time you'd like to apply common styling elements to other widgets inside of your view.
developer.school Newsletter
Join the newsletter to receive the latest updates in your inbox.