我正在努力使用其GlobalKey获取Widget的高度。 在呈现Layout之后调用获取高度的函数以确保上下文可用但key.currentState和key.currentContext仍然返回null。
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget{
@override
State<StatefulWidget> createState() => new TestPageState();
}
class TestPageState extends State<TestPage>{
final TestWidget testWidget = new TestWidget();
@override
initState() {
//calling the getHeight Function after the Layout is Rendered
WidgetsBinding.instance
.addPostFrameCallback((_) => getHeight());
super.initState();
}
void getHeight(){
final GlobalKey key = testWidget.key;
//returns null:
final State state = key.currentState;
//returns null:
final BuildContext context = key.currentContext;
//Error: The getter 'context' was called on null.
final RenderBox box = state.context.findRenderObject();
print(box.size.height);
print(context.size.height);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: testWidget,
);
}
}
class TestWidget extends StatefulWidget{
@override
Key get key => new GlobalKey<TestWidgetState>();
@override
State<StatefulWidget> createState() => new TestWidgetState();
}
class TestWidgetState extends State<TestWidget>{
@override
Widget build(BuildContext context) {
return new Container(
child: new Text("Test", style: const TextStyle(fontSize: 32.0, fontWeight: FontWeight.bold),),
);
}
}
答案 0 :(得分:3)
您需要使用窗口小部件构造函数中的super
将该键分配给窗口小部件。不要将其添加为字段。
Key
也必须保持不变。
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => new TestPageState();
}
class TestPageState extends State<TestPage> {
final key = new GlobalKey<TestWidgetState>();
@override
initState() {
//calling the getHeight Function after the Layout is Rendered
WidgetsBinding.instance.addPostFrameCallback((_) => getHeight());
super.initState();
}
void getHeight() {
//returns null:
final State state = key.currentState;
//returns null:
final BuildContext context = key.currentContext;
//Error: The getter 'context' was called on null.
final RenderBox box = state.context.findRenderObject();
print(box.size.height);
print(context.size.height);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new TestWidget(key: key),
);
}
}
class TestWidget extends StatefulWidget {
TestWidget({Key key}) : super(key: key);
@override
State<StatefulWidget> createState() => new TestWidgetState();
}
class TestWidgetState extends State<TestWidget> {
@override
Widget build(BuildContext context) {
return new Container(
child: new Text(
"Test",
style: const TextStyle(fontSize: 32.0, fontWeight: FontWeight.bold),
),
);
}
}
答案 1 :(得分:1)
这样定义您的构造函数:
const MyWidget(GlobalKey key) : super(key:key);
。
框架将BuildContext
和State
对象存储在Widget.key
字段中,该字段由构造函数而不是任意的key
字段传递给对象。