In this example, I will share how to get height of a Widget using its GlobalKey in flutter. You need to assign that key to a widget using super in the widget constructor. Not add it as a field. That Key also must be constant.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 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), ), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.