在SafeArea中获取小部件高度的正确方法 [英] proper way to get widget height in SafeArea

查看:427
本文介绍了在SafeArea中获取小部件高度的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取小部件的高度,但它会打印相同的值

I'm trying to get the height of widget but it prints the same values

I/flutter (19253): full height: 976.0
I/flutter (19253): safe height: 976.0

我猜想第二个值应该较小,因为Container放置在状态栏下方.我做错了什么? 我需要高度,因为在此容器中将是Wrap小部件(实际上是ReorderableWrap https://pub .dartlang.org/packages/reorderables#-readme-tab- ),包含36张卡片,3行乘12张卡片,卡片高度必须为其容器的1/3.

I guessed the second value should be smaller because the Container placed below the status bar. What I'm doing wrong? I need height because in this container will be Wrap widget (actually ReorderableWrap https://pub.dartlang.org/packages/reorderables#-readme-tab-) with 36 cards, 3 rows by 12 cards and cards height must be 1/3 of its container.

我没有找到好的可重排序网格.但是无论如何,我的问题是,为什么安全区域中的容器与填充整个屏幕的容器具有相同的高度?

I didn't find good Reorderable Grid. But anyway my question why a Container in a safe area has the same height as Container that fills the entire screen?

import 'package:flutter/material.dart';

void main() {
  runApp(_MyApp());
}

class _MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(body: _Body()),
    );
  }
}

class _Body extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('full height: ${MediaQuery.of(context).size.height}');
    return Container(
      constraints: BoxConstraints.expand(),
      decoration: BoxDecoration(color: Colors.red),
      child: SafeArea(
        child: _SafeHeightWidget(),
      ),
    );
  }
}

class _SafeHeightWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('safe height: ${MediaQuery.of(context).size.height}');
    return Container(
      color: Colors.lightBlue,
    );
  }
}

推荐答案

在这种情况下,您始终可以使用LayoutBuilder.

You can always use LayoutBuilder for such cases.

child: SafeArea(
        child: new LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              // constraints variable has the size info
              return Container();
            }
        ),
      ),

了解更多信息: https://www.youtube.com/watch?v=IYDVcriKjsw

这篇关于在SafeArea中获取小部件高度的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆