美文网首页
flutter 获取 widget 的高度

flutter 获取 widget 的高度

作者: Faith_K | 来源:发表于2020-11-30 16:06 被阅读0次

普通widget 可以使用 _globalKey.currentContext.size.height 直接获取,如果获取CustomScrollView slivers 子元素的高度 可以使用 final listHeight = listGlobalKey.currentContext.findRenderObject().semanticBounds.size.height;
以下范例

import 'package:flutter/material.dart';
class WidgetHeight extends StatefulWidget {
  @override
  _WidgetHeightState createState() => _WidgetHeightState();
}

class _WidgetHeightState extends State<WidgetHeight> {
  GlobalKey _globalKey = GlobalKey();

  GlobalKey listGlobalKey = GlobalKey();

  void _getWidgetHeight(){

    final containerHeight = _globalKey.currentContext.size.height;
//   可以获取 slivers 列表的高度
    final listHeight = listGlobalKey.currentContext.findRenderObject().semanticBounds.size.height;

    print('containerHeight ==${containerHeight} listHeight==${listHeight}');
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          Container(
            key: _globalKey,
            color: Colors.white,
            padding: EdgeInsets.all(50),
            child: Text('height'),
          ),
          Expanded(
            key: listGlobalKey,
              child: ListView.builder(
              itemCount: 10,
              itemBuilder: (context,index){
                return Text('celll${index}');
              })),
          FlatButton(onPressed: _getWidgetHeight, child: Text('获取widget的高度')),
          SizedBox(height: 160,),
        ],
      ),
    );
  }
}

相关文章

网友评论

      本文标题:flutter 获取 widget 的高度

      本文链接:https://www.haomeiwen.com/subject/vmarwktx.html