0

我有一个固定高度为 100 的水平列表栏(在 Column 内使用)。高度 100 适合 iPhone8。但由于 100 高度限制,iPhone-X 中的像素溢出。如果我做到140,两者都很好。但是在 iphone8 中该栏看起来并不好。所以我想要一台设备的高度为 120,而另一台设备的高度为 140。我想我可以使用 ConstrainedBox 来实现它,如下所示:

ConstrainedBox(constraints: BoxConstraints(minHeight: 100, maxHeight: 140), child: ListView(...))

但是 listview 一直以 140 高度运行。那么如何实现不同设备的动态高度约束呢?

示例小部件:

class MyHorizontalBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 100, // 140
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          _myCard(),
          _myCard(),
          _myCard(),
        ],
      ),
    );
  }

  Widget _myCard(){
    return Container(
      width: 115,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Top', style: TextStyle(fontSize: 12)),
          Text('Middle', style: TextStyle(fontSize: 25)),
          Text('Bottom', style: TextStyle(fontSize: 18)),
        ],
      ),
    );
  }
}
4

3 回答 3

1

尝试使用 MediaQuery.of(context).size.height 或 width 代替恒定的高度和宽度。

于 2020-12-23T06:27:14.837 回答
0

您可以使用LayoutBuilder小部件。但是这些问题通常可以通过灵活的布局来解决。

例如,将您的水平条高度定义为可用高度的 1/3。

于 2020-12-23T06:49:04.407 回答
0

使用 MediaQuery.of(context)

试试下面的代码。

class MyHorizontalBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double magicNumber = 5; // Try playing with this number to get the appearence. 
    return SizedBox(
      height: MediaQuery.of(context).size.height / magicNumber, 
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          _myCard(),
          _myCard(),
          _myCard(),
        ],
      ),
    );
  }

  Widget _myCard() {
    return Container(
      width: 115,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
              Text('Top', style: TextStyle(fontSize: 12)),
              Text('Middle', style: TextStyle(fontSize: 25)),
              Text('Bottom', style: TextStyle(fontSize: 18)),
            ],
          ),
        );
      }
    }

尝试使用变量 magicNumber。

于 2020-12-23T08:16:04.297 回答