Flutter Container Margin
To set specific margin for Container widget in Flutter, set margin
property of the Container with the required EdgeInsets value.
Syntax
Container (
margin: EdgeInsets.all(50),
),
Example
Flutter Application with two Container widgets.
The margin for the inner Container widget is set to 20
. Outer Container widget is only for demonstrating the margin of inner Container widget, and is not mandatory in an actual application.
Margin extends outwards of the Container widget, and is independent of width/height of the Container widget.
main.dart
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// main application widget
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Application';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
),
);
}
}
/// stateful widget that the main application instantiates
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// private State class that goes with MyStatefulWidget
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
@override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.lightGreen,
child: Container(
width: 150,
height: 150,
margin: const EdgeInsets.all(20),
color: Colors.blue,
),
),
);
}
}
Screenshot
Let us now change the margin to EdgeInsets.all(50)
, and observe the output.