在颤动中使用其GlobalKey获取小部件的高度

在颤动中使用其GlobalKey获取小部件的高度,第1张

在颤动中使用其GlobalKey获取小部件的高度

您需要

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),      ),    );  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5031643.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存