Expanded 是 Flutter 中的一个布局小部件,用于在 Row、Column 或 Flex 中扩展子部件以填充可用空间。它可以用来控制子部件在主轴方向上的大小。
当你在 Row 或 Column 中使用 Expanded 时,它会将子部件拉伸以填充剩余的可用空间。在 Row 中,Expanded 会在水平方向上扩展子部件;在 Column 中,它会在垂直方向上扩展子部件。
下面是一个简单的示例代码,演示如何使用 Expanded:
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('Expanded Example'),
),
body: Column(
children: <Widget>[
Container(
height: 100,
color: Colors.red,
),
Expanded(
child: Container(
color: Colors.blue,
child: Center(
child: Text(
'This is the Expanded widget',
style: TextStyle(color: Colors.white),
),
),
),
),
Container(
height: 100,
color: Colors.green,
),
],
),
),
);
}
}
在这个示例中,我们创建了一个 Column,其中包含了三个子部件:红色、蓝色和绿色的容器。中间的蓝色容器被包裹在一个 Expanded 小部件中。这意味着蓝色容器将会填充 Column 在垂直方向上的剩余空间,因此它将会占据尽可能多的空间,使得其他容器在垂直方向上靠上下分布。
使用 Expanded 是一种常见的布局技术,可以帮助你创建灵活的、自适应的 UI 布局。