Flutter Widget 之 Expanded(填充佈局)
阿新 • • 發佈:2021-01-15
技術標籤:AndroidFlutterdartwidgetflutter
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,
),
),
],
),
);
}
}
效果如下: