【问题标题】:Flutter, how to set max height to list view itemsFlutter,如何设置最大高度以列出视图项
【发布时间】:2020-12-12 07:43:22
【问题描述】:

我尝试过的如下。

         SizedBox(
           width: MediaQuery.of(context).size.width * 0.88,
           height: MediaQuery.of(context).size.height * 0.42,
             child: ListView.builder(
                   itemCount: 10,                          
                   itemBuilder: (BuildContext context, int index) {
                            return _buildListItem();
                         }),
                   )

和列表小部件

 Widget _buildListItem() {
    return ConstrainedBox(
      constraints: BoxConstraints(
        minHeight: 20,
          maxHeight: 120),
       child:Container(child:Text("Looooongggg textttttttttt 
              the text size is alwayysss different "),
       ),}

我想让列表视图项的大小是动态的,而且最大高度也固定为120。换句话说,无论文本有多长,容器也希望不上到120或更多.

此代码始终只显示最大高度的容器。不管字母多短,

我怎样才能做到这一点?

【问题讨论】:

    标签: flutter flutter-layout


    【解决方案1】:

    试试 IntrinsicHeight 小部件

    Widget _buildListItem() {
        return ConstrainedBox(
          constraints: BoxConstraints(
            minHeight: 20,
              maxHeight: 120),
           child: IntrinsicHeight(child:Container(child:Text("Looooongggg textttttttttt 
                  the text size is alwayysss different "),
           )),}
    

    【讨论】:

    • 谢谢!它完美地工作。我只是想知道,除了这个,你还知道其他方法吗?我只是问我的学习目的。想不到就不用回答了。
    【解决方案2】:

    您可以通过将滚动物理设置为 NeverScrollablePhysics 来实现。通过这样做,列表视图将占用足够的高度,以便其所有子视图都可以放入其中。 例如:-

        ...
        ListView.builder(
          physics:NeverScrollableScrollPhysics(),//this line would the change                               
          itemCount: 10,                          
          itemBuilder: (BuildContext context, int index) {
                  return _buildListItem();
                }),
               ),
        ...
    

    【讨论】:

    • 将列表视图包装在单个子滚动视图小部件中,并在列表视图中启用收缩包装。这将对您有所帮助。
    • 欣赏它。我会参考的
    【解决方案3】:

    使用Container 并将最小、最大高度分配给BoxConstraints

    Container(
            child: ListView.builder(itemBuilder: (BuildContext context, index) {
                return Container(
                  constraints: BoxConstraints(minHeight: 20, maxHeight: 40),
                  color: Colors.red,
                  child: Divider(),
                );
            }, itemCount: itemsList.length,),
          ),
    

    输出:

    【讨论】:

    • 这与我已经在问题中输入的代码几乎相同。除了容器和受约束的属性来回交换。
    • 这将保持最小和最大高度限制,这可行
    • 我只是按照你的建议做了。它不起作用。它总是显示最大高度
    • 那可能是你的孩子太大了,最多40个
    猜你喜欢
    • 2012-11-04
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 2018-07-22
    • 2013-10-01
    • 2017-07-30
    • 1970-01-01
    • 2017-07-22
    相关资源
    最近更新 更多