Flutter中三树模型(Widgets、Element、Render),测量的时候用 GlobalKey作为索引,检索RendeTree的节点,然后获取宽高。 不过Render是跟着生命周期走的,或者干脆Widget还没加到 布局里。你只有一个GlobalKey,这是拿RenderObject就是个null,就拿不到Size。 所以你得监听Widget加到布局里,生成Render Tree,然后去查询size(Demo里的是源自StackOverFlow内的代码)
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
/// size nullable
typedef void OnWidgetSizeChange(Size size);
class MeasureSizeRenderObject extends RenderProxyBox {
Size oldSize;
final OnWidgetSizeChange onChange;
MeasureSizeRenderObject(this.onChange);
@override
void performLayout() {
super.performLayout();
Size newSize = child?.size;
if (oldSize == newSize) return;
oldSize = newSize;
if (WidgetsBinding.instance != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
onChange(newSize);
});
}
}
}
class MeasureSize extends SingleChildRenderObjectWidget {
final OnWidgetSizeChange onChange;
const MeasureSize(
Widget child,
this.onChange, {
Key key,
}) : super(key: key, child: child);
@override
RenderObject createRenderObject(BuildContext context) {
return MeasureSizeRenderObject(onChange);
}
}
调用
return MeasureSize(
Text("Hello"),
(size) {
print("sizeChange: ${size?.height ?? 'null'} -------++++++++++++++--");
});
|