Introduction of Expanded Widget
In Flutter, the Expanded Widget is used to allocate additional space to its child within a Flex parent, typically a Column or Row. It enables the child widget to expand and occupy the available space along the main axis of the parent. The Expanded widget has a few properties that can be customized.
Usage in a Column or Row:
In this example, the Container wrapped with Expanded will take up all the available vertical space between “Widget 1” and “Widget 2” in the Column.
Column( children: [ Text('Widget 1'), Expanded( child: Container( color: Colors.blue, ), ), Text('Widget 2'), ], ),
Flexible Space Allocation:
This Widget flexes to occupy any remaining space after non-flexible widgets have been laid out. If there are multiple Widgets in a Row or Column, they share the available space based on their flex factor.
Row( children: [ Container( width: 50, height: 50, color: Colors.red, ), Expanded( flex: 2, child: Container( color: Colors.blue, ), ), Expanded( flex: 1, child: Container( color: Colors.green, ), ), ], ),
In this example, the second Container will take twice as much horizontal space as the third one due to the flex factors.
Inside a Flex Parent
The Expanded widget is commonly used inside a Flex parent (like Column or Row) to distribute available space among its children.
Row( children: [ Container( width: 50, height: 50, color: Colors.red, ), Expanded( child: Container( color: Colors.blue, ), ), Container( width: 50, height: 50, color: Colors.green, ), ], ),
Final Code: This is the final code with the combination of some above expanded widget properties.
import 'package:flutter/material.dart'; class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Expanded( child: Container( color: Colors.deepPurple, ), ), Expanded( child: Container( color: Colors.teal, ), ), Expanded( child: Container( color: Colors.orangeAccent, ), ), ], ), ); } }
The Expanded widget is a powerful tool for creating flexible and responsive layouts in Flutter, allowing developers to control how space is distributed among different widgets within a parent.
Thank for visiting Hybrid App Development
Posted by Hussam HM