Flutter获取Widget位置信息和状态栏、AppBar高度等


发文时间:2022年04月18日 11:02:41     编辑:Aaron      标签:widget位置获取的方式 541


获取widget的xy值时,若存在appBar则这个偏移值会包含状态栏和AppBar的高度

1、获取手机状态栏的高度

double height= MediaQueryData.fromWindow(WidgetsBinding.instance.window).padding.top;
print('获取手机状态栏的高度 $height');

image.png2、获取AppBar的高度

import 'package:flutter/src/material/constants.dart';

///  * The Material spec on touch targets at .
const double kMinInteractiveDimension = 48.0;

/// The height of the toolbar component of the [AppBar].
const double kToolbarHeight = 56.0;

/// The height of the bottom navigation bar.
const double kBottomNavigationBarHeight = 56.0;

image.png

3、获取widget的XY值信息,y值信息包含状态栏和AppBar的高度

   重点在于要给widget加上GlobalKey(关于key可以看我之前写的“Flutter中Key的原理及使用 LocalKey”),具体代码如下

//定义需要获取widget宽高key
final _key1=GlobalKey();
final _key2=GlobalKey();


//建议封装起来
getWidgetX(GlobalKey key) {
  RenderBox renderBox = key.currentContext.findRenderObject();
  double dx = renderBox.localToGlobal(Offset.zero).dx;
  return dx;
}

getWidgetY(GlobalKey key) {
  RenderBox renderBox = key.currentContext.findRenderObject();
  double dy = renderBox.localToGlobal(Offset.zero).dy;
  return dy;
}

child: Center(
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Container(
        key:_key1,
          width: 150,
          height: 150,
        color: Colors.amber,
        child: Column(
          children: [
            Text('第一个widget'),
            InkWell(
              child: Text('获取X'),
              onTap: (){
                print(this.getWidgetX(_key1));
              },
            )
          ],
        ),
      ),

      Container(
        key:_key2,
        width: 150,
        height: 150,
        color: Colors.red,
        child: Column(
          children: [
            Text('第一个widget'),
            InkWell(
              child: Text('获取Y'),
              onTap: (){
                print(this.getWidgetY(_key2));
              },
            )
          ],
        ),
      ),

    ],

  ),
),

image.png

4、获取widget的宽高 width Height

//获取widget的宽高信息
getWidth(GlobalKey key) {
  RenderBox renderBox = key.currentContext.findRenderObject();
  return renderBox.size.width;
}
getHeight(GlobalKey key) {
  RenderBox renderBox = key.currentContext.findRenderObject();
  return renderBox.size.height;
}

image.png


 

若无特殊说明,此文章为博主原创。
写稿不易,如需转载,请注明出处: https://www.aaroner.cn/art/56.html




SITE MAP

  FOLLOW US