颤振:在改变移动设备的方向时,如何构建移动块的逻辑?



使用 flutter,我需要在移动设备中放置两个块,以便:

  • 垂直位置block_A顶部block_B底部
  • 水平位置block_A左侧block_B右侧

结果的图像


我通过 Wrap 实现了这一点,根据当前屏幕的宽度设置块的宽度,然后 Wrap 自动放下块。但我不确定这是否是正确的决定。

class MainPage extends StatelessWidget {
Widget build(BuildContext context) {
var screenSize = MediaQuery.of(context).size;
double mainBoxWidth = screenSize.width / 100 * (screenSize.width > screenSize.height ? 50 : 100) ;
double mainBoxHeight = screenSize.height / 100 * (screenSize.width > screenSize.height ? 100 : 50) ;
return Scaffold(
body: Center(
child: Wrap(
children: [
Container(
child: Center(
child: Text("block_A"),
),
width: mainBoxWidth,
height: mainBoxHeight,
),

Container(
child: Center(
child: Text("block_B"),
),
width: mainBoxWidth, 
height: mainBoxHeight,           
),
],
),
),
backgroundColor: Colors.green
);
}
}

请告诉我如何正确执行此任务。谢谢。

与 Flutter 中的大多数事情一样,有几种方法可以做到这一点。这是一种方法:

class MainPage extends StatelessWidget {
Widget build(BuildContext context) {
var screenSize = MediaQuery.of(context).size;
final isLandscape = screenSize.width > screenSize.height;
return Scaffold(
body: isLandscape
? Row(
children: _buildChildren(),
)
: Column(
children: _buildChildren(),
),
backgroundColor: Colors.white,
);
}
List<Widget> _buildChildren() {
return [
Expanded(
child: Container(
color: Colors.yellow,
child: Center(
child: Text("block_A"),
),
),
),
Expanded(
child: Container(
color: Colors.green,
child: Center(
child: Text("block_B"),
),
),
),
];
}
}

最新更新