Spacer Widget and Attributes

Spacer Widget and Attributes

ยท

2 min read

The Spacer widget in Flutter is a simple and flexible widget used to create empty space within a Flex container, typically a Row or Column. It takes up any available space along its main axis, pushing its adjacent widgets to either side.

Here's a basic example of how you can use the Spacer widget:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Spacer Widget Example'),
        ),
        body: Row(
          children: [
            Container(
              width: 50.0,
              height: 50.0,
              color: Colors.blue,
            ),
            Spacer(),
            Container(
              width: 50.0,
              height: 50.0,
              color: Colors.green,
            ),
            Spacer(),
            Container(
              width: 50.0,
              height: 50.0,
              color: Colors.red,
            ),
          ],
        ),
      ),
    );
  }
}

In this example, the Spacer() widgets evenly distribute the available space between the three colored containers within the Row. The Spacer takes up any remaining space along the main axis, effectively pushing the adjacent containers to the edges.

Attributes:

The Spacer widget doesn't have specific attributes since it's a simple, stateless widget designed to fill available space. However, its behavior is influenced by the surrounding Flex container and its properties:

  • flex (int): If you want to control how the available space is distributed among multiple Spacer widgets, you can assign a flex factor to each Spacer. The available space is divided among the Spacer widgets based on their flex factors.

      Row(
        children: [
          Spacer(flex: 2),
          Container(
            width: 50.0,
            height: 50.0,
            color: Colors.blue,
          ),
          Spacer(flex: 1),
          Container(
            width: 50.0,
            height: 50.0,
            color: Colors.green,
          ),
          Spacer(flex: 3),
          Container(
            width: 50.0,
            height: 50.0,
            color: Colors.red,
          ),
        ],
      )
    

In this example, the available space is distributed among the three Spacer widgets based on their flex factors (2, 1, and 3). The total flex factor is 2 + 1 + 3 = 6, and each Spacer gets a portion of the available space based on its relative flex factor.

The Spacer widget is handy for creating flexible and responsive layouts, especially within Row and Column widgets, where you want to distribute space among different widgets dynamically.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย