如何在列中同时使用”Expanded”和具有固定高度的”Container”而不产生溢出。

huangapple go评论63阅读模式
英文:

How to use Expanded and a Container with a fixed height together in a column without overflow

问题

以下是您要翻译的代码部分:

Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text('TestApp')),
    body: Column(
      children: [
        Container(
          height: 100,
          color: Colors.red,
        ),
        Expanded(
          child: Container(
            color: Colors.blue,
          ),
        )
      ],
    ),
  );
}

通常情况下,没有问题,但当屏幕的高度小于100时,会发生溢出。我希望高度不会溢出,而是减小。

我尝试过使用SingleChildScrollViewWrap,然后Expanded不可用。并且使用ConstrainedBox来设置MaxHeight为100,仍然会发生溢出。

英文:

Simply put, I want the following code to run without overflow.

Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text('TestApp')),
    body: Column(
      children: [
        Container(
          height: 100,
          color: Colors.red,
        ),
        Expanded(
          child: Container(
            color: Colors.blue,
          ),
        )
      ],
    ),
  );
}

Normally, there is no problem, but when the height of the screen is smaller than 100, overflow happens. Instead of overflowing, I want the height to be reduced.

I tried SingleChildScrollView and Wrap, and then Expanded was unavailable.And using ConstrainedBox to set MaxHeight to 100, still, there was an overflow.

答案1

得分: 0

你可以使用MediaQuery类来避免使用LayoutBuilder

@override
Widget build(BuildContext context) {
  final screenHeight = MediaQuery.of(context).size.height;
  final minHeight = 100;

  return Scaffold(
    body: Column(
      children: [
        Container(
          height: screenHeight < minHeight ? screenHeight : 100,
          color: Colors.red,
        ),
        Expanded(
          flex: screenHeight < minHeight ? 0 : 1,
          child: Container(
            color: Colors.blue,
          ),
        )
      ],
    ),
  );
}
英文:

You can take aid of MediaQuery class, if you want to avoid LayoutBuilder

@override
Widget build(BuildContext context) {
  final screenHeight = MediaQuery.of(context).size.height;
  final minHeight = 100;

  return Scaffold(
    body: Column(
      children: [
        Container(
          height: screenHeight < minHeight  ? screenHeight : 100,
          color: Colors.red,
        ),
        Expanded(
          flex: screenHeight < minHeight  ? 0 : 1,
          child: Container(
            color: Colors.blue,
          ),
        )
      ],
    ),
  );
}

huangapple
  • 本文由 发表于 2023年3月12日 17:07:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定