我们平时在开发中的过程中通常都会获取屏幕或者 widget 的宽高用来做一些事情,在 Flutter 中,我们可以使用如下方法来获取屏幕或者 widget 的宽高。

MediaQuery

一般情况下,我们会使用如下方式去获取 widget 的宽高:

final size =MediaQuery.of(context).size;
final width =size.width;
final height =size.height;
复制代码

但是如果不注意,这种写法很容易报错,例如下面的写法就会报错:

import 'package:flutter/material.dart';

class GetWidgetWidthAndHeiget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final size =MediaQuery.of(context).size;
final width =size.width;
final height =size.height;
print('width is $width; height is $height');
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Width & Height'),
),
body: Container(
width: width / 2,
height: height / 2,
),
),
);
}
}
复制代码

在代码中,我们是想获取屏幕的宽和高,然后将屏幕宽高的一半分别赋值给 Container 的宽和高,但上述代码并不能成功运行,会报如下错误:

flutter: The following assertion was thrown building GetWidgetWidthAndHeiget(dirty):
flutter: MediaQuery.of() called with a context that does not contain a MediaQuery.
flutter: No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
flutter: This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
flutter: a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
复制代码

从错误异常中我们可以大概了解到有两种情况会导致上述异常:

  1. 当没有 WidgetsApp or MaterialApp 的时候,我们使用 MediaQuery.of(context) 来获取数据。
  2. 当我们在当前小部件中使用了上一个小部件的 context,来使用 MediaQuery.of(context) 获取数据的时候。

我们上述的代码很显然是属于第一种情况,也就是说我们在使用 MediaQuery.of(context) 的地方并没有一个 WidgetsApp or MaterialApp 来提供数据。

解决方法就是将 MediaQuery.of(context) 挪到 MaterialApp 内,如下:

import 'package:flutter/material.dart';

class GetWidgetWidthAndHeiget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
} class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final width = size.width;
final height = size.height;
print('width is $width; height is $height');
return Scaffold(
appBar: AppBar(
title: Text('Width & Height'),
),
body: Center(
child: Container(
color: Colors.redAccent,
width: width / 2,
height: height / 2,
),
),
);
}
}
复制代码

运行效果及输出如下:

flutter: width is 414.0; height is 896.0
复制代码

上述代码中,我们获取的是 MaterialApp 的宽高,也就是屏幕的宽高

还有一种是直接使用 dart:ui 包中的 window 对象(这里非常感谢 XuYanjun Android @ 苏宁 提出的方法),这种方法使用起来也比较简单,如下:

import 'dart:ui';

final width = window.physicalSize.width;
final height = window.physicalSize.height;
复制代码

那么如果我们要需要知道上述红色的 Container 容器的宽高怎么办呢?这里我们可以使用 GlobalKey

GlobalKey

使用 GlobalKey 的步骤如下:

  1. 声明一个 GlobalKey final GlobalKey globalKey = GlobalKey();

  2. 给 widget 设置 GlobalKey key: globalKey

  3. 通过 globalKey 来获取该 widget 的 size

    final containerWidth = globalKey.currentContext.size.width;
    final containerHeight = globalKey.currentContext.size.height;
    print('Container widht is $containerWidth, height is $containerHeight');
    复制代码

修改过后的 HomePage 代码如下:

class HomePage extends StatelessWidget {

  final GlobalKey globalKey = GlobalKey();

  void _getWH() {
final containerWidth = globalKey.currentContext.size.width;
final containerHeight = globalKey.currentContext.size.height;
print('Container widht is $containerWidth, height is $containerHeight');
} @override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final width = size.width;
final height = size.height;
print('width is $width; height is $height');
return Scaffold(
appBar: AppBar(
title: Text('Width & Height'),
),
body: Center(
child: Container(
key: globalKey,
color: Colors.redAccent,
width: width / 2,
height: height / 2,
),
),
floatingActionButton: FloatingActionButton(
onPressed: _getWH,
child: Icon(Icons.adjust),
),
);
}
}
复制代码

上述代码中,我们将声明的 globalKey 设置给了 Container , 当我们点击页面中的 FloatingActionButton 的时候,就会使用 globalKey 来获取 Container 的宽高,也就是 _getWH() 中执行的代码。

运行结果及输出如下:

flutter: Container widht is 207.0, height is 448.0
复制代码

如果错误,还请指出,谢谢

完整源码

参考链接

Flutter获取屏幕宽高和Widget大小的更多相关文章

  1. android获取屏幕宽高与获取控件宽高

    获取屏幕宽高 // 获取屏幕宽高(方法1) int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽(像素 ...

  2. vue 获取屏幕宽高 width height

    /**  * 获取屏幕宽高  */ Vue.prototype.getViewportSize = function(){   return {     width: window.innerWidt ...

  3. android 获取屏幕宽高 和 获取控件坐标

    一.获取屏幕宽高: (1). WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE); int width ...

  4. js获取屏幕宽高

    最近想自己实现一个全屏滚动. 结果一开始就遇到了问题.因为不知道如何获取一个页面屏幕的高度. 网上所有的博客都是复制粘贴. 网页可见区域宽:document.body.clientWidth 网页可见 ...

  5. 【Html】网页获取屏幕宽高

    <html> <script> function size(){ document.write( "屏幕分辨率为:"+screen.width+" ...

  6. js 获取屏幕宽高

    网页可见区域宽: document.body.clientWidth 网页可见区域高: document.body.clientHeight 网页可见区域宽: document.body.offset ...

  7. js、jq获取屏幕宽高

    参考资料 JS,Jquery获取各种屏幕的宽度和高度

  8. js 获取图片宽高 和 图片大小

    获取要查看大小的img var img_url = 'http://img5.imgtn.bdimg.com/it/u=4267222417,1017407570&fm=200&gp= ...

  9. Swift 获取屏幕宽高

    let screenh = UIScreen.mainScreen().applicationFrame.size.heightlet screenw = UIScreen.mainScreen(). ...

随机推荐

  1. AlertConfirmDialog【基于AlertDialog的确认取消对话框】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 确认取消对话框,基于AlertDialog.不是基于DialogFragment. 按钮文本可以根据实际情况更换. 效果图 代码分析 ...

  2. Angular开发技巧

    由于之前有幸去参加了ngChina2018开发者大会,听了will保哥分享了Angular开发技巧,自己接触Angular也有差不多快一年的时间了,所以打算对Angular开发中的一些技巧做一个整理 ...

  3. 玩转Spring Cloud之配置中心(config server &config client)

     本文内容导航: 一.搭建配置服务中心(config server) 1.1.git方式 1.2.svn方式 1.3.本地文件方式 1.4.解决配置中包含中文内容返回乱码问题 二.搭建配置消费客户端( ...

  4. 远程连接桌面报:这可能是由于credssp加密oracle修正

      1.Win+R 输入regedit打开注册表 找到对应的以下目录HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Polic ...

  5. C# 设置程序启动项

    托盘图标设置 新建一个NotifyIcon,会在托盘处显示一个图标. NotifyIcon.Icon可以直接设置一个ico图片,也可以延用原有程序的图标. notifyIcon.Icon = Syst ...

  6. EF 查询视图出现重复数据

    解决方案: 由多张表组成的视图,要加实体键.而且实体键组合要能确保唯一性. 个人理解:确保唯一性,一个或多个实体键,实现了复合主键或组合主键的效果. 这样查询是,延迟加载机制,才知道哪些需要重新从数据 ...

  7. 软件开发:网站&视频&书籍&文章推荐(不断更新)

    利用书籍进行系统学习,凭借博客/新闻等资料开阔眼界,辅之以代码及项目实战,并勤加以总结,方可进步. 常用网站: 找英文电子书网站:gen.lib.rus.ec 和 www.jiumodiary.com ...

  8. Ubuntu16.04安装Qt5.12.2

    第一步:下载文件 https://download.qt.io/official_releases/qt/5.12/5.12.2/ 第二步:安装依赖库 sudo apt-get install bui ...

  9. 在 DotNetCore 3.0 程序中使用通用协议方式启动文件关联应用

    问题描述 在传统的基于 .NET Framework 的 WPF 程序中,我们可以使用如下代码段启动相关的默认应用: # 启动默认文本编辑器打开 helloworld.txt Process.Star ...

  10. Windows环境下使用pip install安装lxml库

    lxml是Python语言和XML以及HTML工作的功能最丰富和最容易使用的库.lxml是为libxml2和libxslt库的一个Python化的绑定.它与众不同的地方是它兼顾了这些库的速度和功能完整 ...