首页 > 解决方案 > 如何获取父布局的高度 - Flutter

问题描述

我想要容器的高度

 Container( // how to get height of the container
    child: Text('hello,\nhow to get\nheight of the parent layout'),
 ),

我试试这个

  return LayoutBuilder(
    builder:
        (BuildContext context, BoxConstraints constraints) {
      print(constraints.maxHeight);
      return Container( // how to get height of the container
        child: Text('hello,\nhow to get\nheight of the parent layout'),
      );
    },
  );

高度打印始终为 0 值

标签: flutterflutter-layout

解决方案


关于您的代码段

return LayoutBuilder(
    builder:
        (BuildContext context, BoxConstraints constraints) {
      print(constraints.maxHeight);
      return Container( // how to get height of the container
        child: Text('hello,\nhow to get\nheight of the parent layout'),
      );
    },
  );

您正在尝试获得孩子的大小。要获取父级大小,您需要LayoutBuidler在该小部件上用作子级。

像这样,

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: LayoutBuilder(
      builder: (context, bodyConstraints) {
        print("body height : ${bodyConstraints.maxHeight}");

        return Container(
          height: 200,
          color: Colors.deepOrangeAccent,
          child: LayoutBuilder(
            builder: (context, containerConstraints) {
              print("Container height ${containerConstraints.maxHeight}");

              return Text(
                " body Height: ${bodyConstraints.maxHeight} \n container height: ${containerConstraints.maxHeight}",
              );
            },
          ),
        );
      },
    ));
  }
}

它解决了你的问题吗?


推荐阅读