What is Container in Flutter: Explanation and Example
Container is a versatile widget that lets you create a rectangular visual element. It can hold a child widget and allows you to customize its size, padding, margin, color, border, and more to control layout and appearance.How It Works
Think of a Container as a box you can decorate and resize. It can hold one child widget inside it, like a picture or text, and you can add space around it (margin), space inside it (padding), or change its color and shape. This makes it very useful for building parts of your app's screen.
Just like wrapping a gift in a box with colorful paper and ribbons, a Container wraps its child widget and lets you style it easily. It helps you control where the child sits and how it looks without changing the child itself.
Example
This example shows a Container with a blue background, some padding, and a text inside it. It demonstrates how you can style and size a container easily.
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: Scaffold( body: Center( child: Container( padding: EdgeInsets.all(20), color: Colors.blue, child: Text( 'Hello Container', style: TextStyle(color: Colors.white, fontSize: 18), ), ), ), ), ); } }
When to Use
Use a Container when you want to add space, color, borders, or size constraints around a widget. It is perfect for grouping and styling parts of your UI without changing the child widget itself.
For example, you can use a Container to create buttons with background colors, add margins between elements, or wrap images with borders. It is a basic building block for layout and design in Flutter apps.
Key Points
- Container can hold one child widget.
- It controls size, padding, margin, color, and borders.
- Useful for styling and layout in Flutter UI.
- Acts like a decorated box around content.