What is a Spacer widget?

Spacer widget is used to create spacing between elements inside a Row and Column.

Spacer class constructor

const Spacer({Key key, this.flex = 1})

 

Spacer full Example

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String data = "Pass data";
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: const Text("Flutter app"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(
                height: 50,
                child: Row(
                  children: <Widget>[
                    Container(
                      width: 50,
                      color: Colors.lightBlue,
                    ),
                    const Spacer(),
                    Container(
                      width: 50,
                      color: Colors.lightGreen,
                    ),
                    const Spacer(),
                    Container(
                      width: 50,
                      color: Colors.red,
                    ),
                    Container(
                      width: 50,
                      color: Colors.yellowAccent,
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

What is a Spacer widget?

Leave a Comment