Flutter – Container Widget

Flutter Container widget center aligns its child widget within itself, along vertical and horizontal axes.

Code Snippet

The following is a simple code snippet to create a Container widget with a child.

Container(
  child: someWidget,
)
ADVERTISEMENT

Example

In the following example, we create a Flutter Application with a Container widget. The Container widget has following properties set.

  • height is set to 150.
  • width is set to 200.
  • color is set to green.
  • alignment is set to center.
  • child is set to a Text widget.

main.dart

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Tutorial';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const MyStatefulWidget(),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: <Widget>[
          const SizedBox(height: 10,),
          Container(
            height: 150,
            width: 200,
            color: Colors.green,
            alignment: Alignment.center,
            child: const Text('Container'),
          ),
        ],
      ),
    );
  }
}

Screenshot – iPhone Simulator

Screenshot – Android Emulator

Container Widget Tutorials

The following tutorials deal with specific properties or functionalities of a Container widget.

Conclusion

In this Flutter Tutorial, we learned what Container widget is, and how to use it in our Flutter application, with examples.