我在Sizedbox小工具中有一个文本.我给它一个特定的宽度来调整大小,但我不能给它一个高度.每当文本变大时,大小框的高度都会增加.

我怎么才能动态地知道这个高度?(使用mediaQuery或类似的东西)有没有办法把它存储在一个变量中?

我try 了一些方法,但到目前为止还不能得到结果.

最后,我使用了这个方法

import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Size _getChildSize(BuildContext context) {
    final widget = context.findRenderObject() as RenderBox?;

    return widget != null ? widget.size : Size.zero;
  }

  @override
  Widget build(BuildContext context) {
    final _key = GlobalKey();
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          Container(
            height: 50,
            width: 100,
            color: Colors.red,
            key: _key,
          ),
          Container(
            color: Colors.green,
            // key: _key,
          ),
          TextButton(
              onPressed: () {
                Size size = _getChildSize(context);

                print(size.height);
              },
              child: Text('olcunu gotur')),
          Container(
            //height: 875.4,
            height: 10,
            width: 411.4,
            color: Colors.indigo,
          )
        ],
      ),
    );
  }
}

推荐答案

您可以使用findRenderObject()方法获取任意Widget的大小:

  //declare global key
   final _key = GlobalKey();

  // pass it to the desired widget in a widget tree
   SizedBox(key: _key)

  //call _getChildSize method, this should return the size of above SizedBox. Make sure to call this method after the first frame
  final size = _getChildSize(_key.currentContext);

  Size _getChildSize(BuildContext context) {
    
      final widget = context.findRenderObject() as RenderBox?;

      return widget != null ? widget.size : Size.zero;
 
  }

Flutter相关问答推荐

Flutter在创建时为提供者调用初始化函数

TextFormfield无法与自动路由一起正常工作

Flutter 隔离.使用多个参数运行

如何使文本表格域在抖动中变圆?

无法在仿真器上运行Flutter 项目-文件名太长错误

为什么用户界面不会在Flight中的复选框中更改?

Flutter为什么不;没有ListView.iterable()构造函数?

在带有 flutter 的 Native Android 中,EventChannel.EventSink 始终为 null

在 flutter 的列中使用 Expanded 时出现渲染 Flex 错误

NotifierProvider 每次更新都会重新构建并且值不更新

Flutter 未处理的异常 - 对 null 值使用 Null 判断运算符

如何在 Flutter 中使用 drawLine() 和 drawCircle() 绘制等距离的 4 条线

如何使用 Rrect 或类似工具在 flutter 中绘制梯形线?

在 Flutter 中,您什么时候应该更喜欢Widget继承而不是组合?

如何在 SingleChildScrollView 小部件中管理自定义小部件状态

将 onSaved(value) 从自定义 TextFormField 小部件传递给另一个?

有没有办法帮助我修复类型 null 不是 Map 类型的子类型?

Flutter 小部件中的视图和逻辑分离

Flutter .replaceFirst(或全部)不起作用

Flutter 在滚动期间保持某些元素固定?