Expanded Widget and Attributes

Expanded Widget and Attributes

ยท

2 min read

The Expanded widget in Flutter is used within a Row, Column, or Flex to expand a child widget to fill the available space along the main axis. It's commonly used to create flexible layouts where widgets can dynamically adjust their sizes based on available space.

Attributes:

  1. flex (int):

    • The flex factor to be used when determining how much space should be allocated to the child. If not specified, it defaults to 1.0. If the flex factor is higher for one child compared to others, it will receive more space along the main axis.

Example:

import 'package:flutter/material.dart';

class ExpandedExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Expanded Widget Example'),
      ),
      body: Column(
        children: [
          Container(
            color: Colors.blue,
            height: 100,
            width: 200,
            child: Center(child: Text('Fixed Size Container')),
          ),
          Expanded(
            flex: 2,
            child: Container(
              color: Colors.green,
              child: Center(child: Text('Expanded Container')),
            ),
          ),
          Container(
            color: Colors.yellow,
            height: 100,
            width: 200,
            child: Center(child: Text('Fixed Size Container')),
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: ExpandedExample(),
  ));
}

Explanation:

  • In this example, an Expanded widget is used within a Column to make a container expand to fill the available vertical space.

  • The flex property is set to 2 for the Expanded widget, indicating that it should receive twice as much space as other children in the Column.

  • As a result, the green container inside the Expanded widget expands to fill the available space along the vertical axis.

  • The blue and yellow containers above and below the Expanded widget remain fixed in size.

Did you find this article valuable?

Support Vinit Mepani by becoming a sponsor. Any amount is appreciated!

ย