How to Add Margins to a Widget in Flutter

Margins are required to align and place components of your user interface properly and neatly. In this blog post let’s check how to add margins to a widget in Flutter.

I had already posted on how to add padding to a widget in flutter. In order to set margins to a widget, you need to wrap that widget with Container widget. The Container has a property named margin.

Hence, you can add margins to a widget as given below:

Container(
        margin: EdgeInsets.only(left:30.0, top:20.0,right:30.0,bottom:20.0),
        child: Text("Check out my margins!"),
      )

If you want the same margin for all edges then you can use the following snippet.

Container(
        margin: EdgeInsets.all(30.0),
        child: Text("Check out my margins!"),
      )

Following is the complete flutter example to use margins.

import 'package:flutter/material.dart';


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


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Body()
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class Body extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Padding Example'),
      ),
      body: Container(
        margin: EdgeInsets.only(left:30.0, top:20.0,right:30.0,bottom:20.0),
        child: Text("Check out my margins!"),
      ),
    );
  }
}

Following is the output screenshot of the flutter example.

Leave a Comment

Your email address will not be published. Required fields are marked *