一尘不染

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

flutter

我正在努力使用其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),),
    );
  }
}

阅读 566

收藏
2020-08-13

共1个答案

一尘不染

您需要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),
      ),
    );
  }
}
2020-08-13