可以在列表中使用 if
,实现 conditional rendering,列表里的 if
没有花括号 { }
:
children: <Widget>[
if (isLandscape)
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Show Chart'),
Switch(
value: _showCart,
onChanged: (val) {
setState(() {
_showCart = val;
});
}),
],
),
if (!isLandscape)
Container(
height: (MediaQuery.of(context).size.height -
appBar.preferredSize.height -
MediaQuery.of(context).padding.top) *
0.3,
child: Chart(recentTransactions: _recentTransactions),
),
if (!isLandscape) txListWidget,
if (isLandscape)
_showCart
? Container(
height: (MediaQuery.of(context).size.height -
appBar.preferredSize.height -
MediaQuery.of(context).padding.top) *
0.7,
child: Chart(recentTransactions: _recentTransactions),
)
: txListWidget
],
其中,isLandscape
用于判断手机是否处于横屏模式 landscape mode:
@override
Widget build(BuildContext context) {
// 判断设备方向,是否出于横屏模式:
final isLandscape =
MediaQuery.of(context).orientation == Orientation.landscape;
final appBar = AppBar(
title: Text(
'Personal Expenses All',
),
actions: <Widget>[
IconButton(
onPressed: () => _startAddNewTransaction(context),
icon: Icon(Icons.add))
],
);