首页 > 解决方案 > Flutter:具有不同高度约束的水平 ListView 视图

问题描述

我有一个固定高度为 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)),
        ],
      ),
    );
  }
}

标签: flutterflutter-layout

解决方案


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


推荐阅读