Flutter - Container Cheat Sheet

Flutter - Container Cheat Sheet

When it comes to UI development in Flutter, the Container widget is an essential component. It provides a convenient way to control the layout and styling of your app's elements. In this cheat sheet, we will explore various properties and use cases of the Container widget.

Table of Contents

Container Properties

Alignment

The alignment property allows you to specify how the child should be aligned within the container. It takes an instance of the Alignment class.

Container(
  alignment: Alignment.center,
  child: Text('Centered Text'),
)

Padding

The padding property defines the padding around the child widget.

Container(
  padding: EdgeInsets.all(16.0),
  child: Text('Padded Text'),
)

Margin

The margin property controls the spacing around the container.

Container(
  margin: EdgeInsets.all(16.0),
  child: Text('Margin Text'),
)

Width and Height

You can specify the width and height of the container using the width and height properties.

Container(
  width: 200.0,
  height: 200.0,
  child: Text('Fixed Size Container'),
)

Decoration

The decoration property allows you to customize the visual appearance of the container. You can set properties like color, borderRadius, and boxShadow to achieve the desired look.



Container(
  width: 200.0,
  height: 200.0,
  decoration: BoxDecoration(
    color: Colors.blue,
    borderRadius: BorderRadius.circular(10.0),
    boxShadow: [
      BoxShadow(
        color: Colors.black.withOpacity(0.3),
        blurRadius: 5.0,
        spreadRadius: 2.0,
      ),
    ],
  ),
  child: Text('Decorated Container'),
)


Container Examples

Example 1: Colored Box

This example demonstrates how to create a colored box using the Container widget.

Container(
  width: 200.0,
  height: 200.0,
  color: Colors.blue,
)

Example 2: Rounded Corners

You can easily round the corners of a container using the borderRadius property.

Container(
  width: 200.0,
  height: 200.0,
  decoration: BoxDecoration(
    color: Colors.red,
    borderRadius: BorderRadius.circular(10.0),
  ),
)

Example 3: Gradient Background

Creating a gradient background is also straightforward with the Container widget.

Container(
  width: 200.0,
  height: 200.0,
  decoration: BoxDecoration(
    gradient: LinearGradient(
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
      colors: [Colors.red, Colors.blue],
    ),
  ),
)



Conclusion

The Container widget in Flutter is a powerful tool for controlling the layout and appearance of your app's UI elements. By understanding its various properties and examples, you can create visually appealing and responsive designs. Experiment with different combinations of properties to achieve the desired look and feel for your app.

Remember to refer to the official Flutter documentation for more in-depth information and additional examples.

Previous Post Next Post