flutter 获取屏幕宽度
时间: 2024-11-12 07:16:06 浏览: 48
在Flutter中获取屏幕宽度,你可以使用`MediaQuery`这个API。首先导入`dart:ui`库,然后在`StatefulWidget`或`State`中添加如下代码:
```dart
import 'package:flutter/material.dart';
class ScreenWidthExample extends StatefulWidget {
@override
_ScreenWidthExampleState createState() => _ScreenWidthExampleState();
}
class _ScreenWidthExampleState extends State<ScreenWidthExample> {
double screenWidth;
@override
void initState() {
super.initState();
MediaQuery.query(window: window).then((query) {
screenWidth = query.size.width;
setState(() {});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Screen width is $screenWidth pixels'),
),
);
}
}
```
在这个例子中,我们通过`initState()`方法查询当前窗口的尺寸,并将宽度赋值给`screenWidth`变量。然后,在UI构建阶段显示屏幕宽度。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)