将元素调整为屏幕宽度/高度的百分比 [英] Sizing elements to percentage of screen width/height
问题描述
是否有一种简单的(非 LayoutBuilder)方法可以根据屏幕尺寸(宽度/高度)来调整元素的大小?例如:如何将 CardView 的宽度设置为屏幕宽度的 65%.
Is there a simple (non-LayoutBuilder) way to size an element relative to screen size (width/height)? For example: how do I set the width of a CardView to be 65% of the screen width.
它不能在 build
方法内完成(显然)所以它必须推迟到构建后.有没有更喜欢的地方可以放置这样的逻辑?
It can't be done inside the build
method (obviously) so it would have to be deferred until post build. Is there a preferred place to put logic like this?
推荐答案
FractionallySizedBox
也可能有用.您也可以直接从 MediaQuery.of(context).size
中读取屏幕宽度,并基于此创建一个大小的框
FractionallySizedBox
may also be useful.
You can also read the screen width directly out of MediaQuery.of(context).size
and create a sized box based on that
MediaQuery.of(context).size.width * 0.65
如果您真的想将大小设置为屏幕的一小部分,而不管布局如何.
if you really want to size as a fraction of the screen regardless of what the layout is.
这篇关于将元素调整为屏幕宽度/高度的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!