In Flutter, the Flexible widget is a layout widget that allows its child widget to take up any remaining space in the parent widget, such as a Row or Column. It is a versatile widget that helps create responsive layouts using Flexible Widget in Flutter
Properties of Flexible Widget
Here are the key properties of the Flexible widget:
- child: The child widget that will take up the remaining space.
- flex: An optional integer that determines the proportion of space allocated to the child widget. Default is 1.
How Flexible Widget Works
Here’s how the Flexible widget works:
- The Flexible widget is wrapped around a child widget.
- The parent widget (e.g., Row or Column) allocates space to its children.
- The Flexible widget takes up any remaining space in the parent widget.
- If multiple Flexible widgets are used, the flex property determines the proportion of space allocated to each child.
Key Differences
Here are the key differences between Flexible and Expanded:
Feature | Flexible | Expanded |
---|---|---|
Takes up remaining space | Yes | Yes |
Can shrink | Yes | No |
Flex factor | Optional | Required |
Use Cases for Flexible Widget
Here are some common use cases for the Flexible widget:
- Responsive Layouts: Create layouts that adapt to different screen sizes.
- Dynamic Content: Allocate space dynamically among multiple child widgets.
- Scrolling Lists: Use Flexible widget with ListView or SingleChildScrollView.
- Complex Layouts: Combine Flexible widget with other layout widgets.
Example:
import 'package:flutter/material.dart';
class FlexibleWidgetExample extends StatefulWidget {
@override
State<FlexibleWidgetExample> createState() => _FlexibleWidgetExampleState();
}
class _FlexibleWidgetExampleState extends State<FlexibleWidgetExample> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: [
Flexible(
flex: 1,
child: Container(
color: Colors.red,
),
),
Flexible(
flex: 2,
child: Container(
color: Colors.blue,
),
),
Flexible(
flex: 3,
child: Container(
color: Colors.green,
),
),
],
),
);
}
}