gpt4 book ai didi

flutter - 如何在 Flutter 中获取屏幕的中心偏移量?

转载 作者:行者123 更新时间:2023-12-05 08:45:57 24 4
gpt4 key购买 nike

我正在使用堆栈平移文本,使用 Offset Positioned 小部件。我想获得中心的偏移量。我试过了

offset = Offset(screenWidth/2, screenHeight/2);

但这行不通。有没有其他方法可以获得中心坐标/偏移量?

最佳答案

作为pskink commented , 使用 LayoutBuilder 作为父级;和 Jared Anderton's answer很好,但它会计算 Scaffold 主体,而不考虑其他属性,如 appBar。还有 Hrvoje Čukman's answer满足您的要求。

另一件事可以通过使用 Stack(alignment: Alignment.center 来完成。它将对齐未对齐的 child 。

父部件是 LayoutBuilder .

Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
Offset centerOffset =
Offset(constraints.maxWidth / 2, constraints.maxHeight / 2);
return Scaffold(

另一种选择是获取 windowSize来自 dart:ui

final Size windowSize = MediaQueryData.fromWindow(window).size;
late Offset screenOffset =
Offset(windowSize.width / 2, windowSize.height / 2);
class CenterOffset extends StatelessWidget {
const CenterOffset({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
final Size windowSize = MediaQueryData.fromWindow(window).size;
late Offset screenOffset =
Offset(windowSize.width / 2, windowSize.height / 2);
return LayoutBuilder(
builder: (context, constraints) {
Offset centerOffset =
Offset(constraints.maxWidth / 2, constraints.maxHeight / 2);
return Scaffold(
appBar: AppBar(),
body: LayoutBuilder(
builder: (context, chConstraints) {
Offset bodyBasedCenter = Offset(
chConstraints.maxWidth / 2, chConstraints.maxHeight / 2);
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("window based center $screenOffset"),
Text("Parent based center $centerOffset"),
Text("body based center $bodyBasedCenter"),
],
),
);
},
));
},
);
}
}

Enter image description here

关于flutter - 如何在 Flutter 中获取屏幕的中心偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70888776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com