以下是包含堆栈和其中一些定位小部件的代码。
Stack(
children: [
Positioned(
top: 50,
bottom: 0,
left: 30,
child: Text(
'Mon-Sat',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
Positioned(
top: 70,
bottom: 0,
left: 30,
child: Text(
'11:00 PM',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
Positioned(
top: 0,
bottom: 0,
left: 0,
right: 0,
child: Image.asset(Images.calendar),
),
],
)
现在,此 UI 代码在特定的 6 英寸屏幕上运行良好,但在较小的屏幕上,定位元素会更改其位置(如预期)。
那么,我如何在不同的屏幕尺寸上处理这个定位元素
最佳答案
您可以找到应用程序运行的屏幕的高度和宽度,然后指定顶部、左侧、高度和宽度的相对位置。下面的代码演示了 MediaQuery.of(context).size 的使用,您可以使用它来查找屏幕的宽度和高度。
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) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
double side = height * 0.10;
return Stack(
children: [
Positioned(
top: height * 0.10,
left: width * 0.10,
child: Container(height: side, width: side, color: Colors.red),
),
Positioned(
top: height * 0.10,
left: width * 0.70,
child: Container(height: side, width: side, color: Colors.green),
),
Positioned(
top: height * 0.70,
left: width * 0.70,
child: Container(height: side, width: side, color: Colors.red),
),
Positioned(
top: height * 0.70,
left: width * 0.10,
child: Container(height: side, width: side, color: Colors.green),
),
],
);
}
}
关于flutter - 如何在 Flutter 中处理不同屏幕尺寸上的定位元素(在 Stack 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64648734/