[英]Flutter how to place a widget relative to another widget on screen?
您可以使用 positioned with stack 并放置在任何您想要的地方。 在 dartpad 中复制并尝试此代码。
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
top: 100,
child: Container(
width: MediaQuery.of(context).size.width,
height: 250, color: Colors.yellow)),
Positioned(
top: 60,
right: 20,
child: Icon(Icons.close, size: 32)),
]
);
}
}
这是一个带有Column
小部件的类似 UI,您可以在Column
内的黄色框下方添加一个SizedBox
,其高度与Icon
相同,以便黄色框看起来居中。
因此,我们可以避免在Positioned
小部件中硬编码值(这会影响响应式 UI)
这是代码片段。
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
double iconSize = 32;
return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
Container(
alignment: Alignment.centerRight,
height: iconSize,
child: Icon(Icons.close, size: iconSize),
),
Container(
width: MediaQuery.of(context).size.width,
height: 250,
color: Colors.yellow,
),
SizedBox(height: iconSize)
]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.