Flutter 中获取屏幕以及 Widget 的宽高
在Flutter中,获取屏幕的宽高可以通过window.physicalSize
得到,而获取Widget的宽高通常是在Widget的build
方法中通过context
获取。
以下是示例代码:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
double screenWidth = 0.0;
double screenHeight = 0.0;
double widgetWidth = 0.0;
double widgetHeight = 0.0;
@override
void initState() {
super.initState();
// 获取屏幕的宽高
WidgetsBinding.instance.addPostFrameCallback(_getScreenSize);
}
void _getScreenSize(_) {
final size = window.physicalSize;
screenWidth = size.width;
screenHeight = size.height;
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
widgetWidth = constraints.maxWidth;
widgetHeight = constraints.maxHeight;
return Container(
color: Colors.blue,
child: Center(
child: Text(
'Screen Width: $screenWidth\nScreen Height: $screenHeight\n'
'Widget Width: $widgetWidth\nWidget Height: $widgetHeight',
style: TextStyle(color: Colors.white, fontSize: 18),
),
),
);
},
);
}
}
在这个示例中,_MyWidgetState
类首先在initState
方法中获取屏幕的宽高,然后在build
方法中使用LayoutBuilder
来获取MyWidget
的宽高。这些值随后被显示在Text
小部件中。
评论已关闭