普通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,),
],
),
);
}
}
网友评论