get height of a Widget using its GlobalKey in flutter

前端 未结 2 738
夕颜
夕颜 2020-12-28 11:28

I am struggling getting the height of a Widget using its GlobalKey. the function that is getting the height is called after the Layout is rendered to make sure the context i

相关标签:
2条回答
  • 2020-12-28 11:49

    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.

    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),
          ),
        );
      }
    }
    
    0 讨论(0)
  • 2020-12-28 12:10

    Define your constructor like this:

    const MyWidget(GlobalKey key) : super(key:key);.

    The framework stores the BuildContext and State object in the Widget.key field which is passed into the object by constructor instead of an arbitary key field.

    0 讨论(0)
提交回复
热议问题