All Articles

What is a Container in Flutter?

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.

Introduction

Using the Container

Let’s use the following piece of code as a starting point for our application:

import 'package:flutter/material.dart';

void main() => runApp(new MaterialApp(title: 'Containers', home: new Home()));

class Home extends StatelessWidget {
  
  Widget build(BuildContext context) {
    // TODO: implement build
    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 color

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 another Container 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.

Published 7 Apr 2018

Learn to create cross platform native applications with the Flutter UI Framework.
Paul Halliday on Twitter