Flutter的Expanded布局与Android布局中weight属性类似,可以设置占满剩余空间。
1. Expanded构造方法:
const Expanded({
Key key,
int flex = 1, //占比
@required Widget child,
}) : super(key: key, flex: flex, fit: FlexFit.tight, child: child);
示例:
import 'package:flutter/material.dart';
class ExpandedTestPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Expanded'),
),
body: Column(
children: <Widget>[
_widget1(),
SizedBox(
height: 20,
),
_widget2(),
SizedBox(
height: 20,
),
_widget3(),
SizedBox(
height: 20,
),
_widget4(),
],
),
);
}
//1.当Row中的组件不使用Expanded的时候
Widget _widget1() {
return Container(
color: Colors.green,
child: Row(
children: <Widget>[
Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
],
),
);
}
//2.将Row中的第一个组件使用Expanded包裹
Widget _widget2() {
return Container(
color: Colors.green,
child: Row(
children: <Widget>[
Expanded(
child: Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
],
),
);
}
//3.使用Expanded实现Row中所有组件平均分配剩余空间
Widget _widget3() {
return Container(
color: Colors.green,
child: Row(
children: <Widget>[
Expanded(
child: Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
Expanded(
child: Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
Expanded(
child: Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
],
),
);
}
//4.将一个组件设置成其它组件的两倍大小
Widget _widget4() {
return Container(
color: Colors.green,
child: Row(
children: <Widget>[
Expanded(
child: Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
Expanded(
flex: 2,
child: Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
Expanded(
child: Image.asset(
"resource/images/my_image.jpg",
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
],
),
);
}
}
效果如下: