Container Widget

What is Container Widget?

A widget class that allows you to customize its child widget.

Below are some of its capabilities:

  1. To add the margins to Text widget place it in a Container.
  2. To add padding around the Row, place entire Row inside the Container widget.
  3. To change the device's background, place the entire layout inside the Container.
  4. You can also add the borders, rounded border by placing widget inside the Container.
  5. Add background color or image.

A convenience widget that combines common painting, positioning, and sizing widgets.

Default Constructor

The default constructor creates a widget that combines common painting, positioning, and sizing widgets.

Container(
        decoration:
        height:
        width:
        child:
      );

Constructor Parameters

It contains many input parameters which can be configured to change its behavior and appearance.

The decoration parameter is to paint behind the child.

The height parameter is to add height of the container.

The width parameter is to add width of the container.

The child parameter is to add the widget below Container widget in the tree.

Code snippet

The following code snippet shows how to configure Container widget.

Container(
        decoration: BoxDecoration(color: Colors.black),
        height: 100.0,
        width: 100.0,
        child: Text(
          'Hello, world!',
          textDirection: TextDirection.ltr,
        ),
      )

Demo Code

This example shows how to place the Text widget inside the Container widget and apply height, width and background color black.

import 'package:flutter/material.dart';

// Container widget example
class ContainerDemo extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        decoration: BoxDecoration(color: Colors.black),
        height: 100.0,
        width: 100.0,
        child: Text(
          'Hello, world!',
          textDirection: TextDirection.ltr,
        ),
      ),
    );
  }
}

void main() {
  runApp(ContainerDemo());
}

The BoxDecoration class provides a variety of ways to draw a box.