在 Column Flutter 中居中展开 ListView [英] Center Expanded ListView inside Column Flutter

查看:110
本文介绍了在 Column Flutter 中居中展开 ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个布局,其中顶部和底部有两个 Text 对象,它们保持静止,一个 ListView 在它们的中心.

I'm trying to build a layout where there are two Text objects at the top and bottom which stays stationery and a ListView at their center.

这是屏幕的代码

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 40.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                margin: EdgeInsets.symmetric(vertical: 40.0),
                child: Text(
                  DateFormat("hh:mm 'PM ,'  MMMM d").format(DateTime.now()),
                  style: Theme.of(context).textTheme.title,
                ),
              ),
              Expanded(
                child: ListView.builder(
                  itemCount: 4,
                  itemBuilder: (BuildContext context, int index) =>
                      CustomAppText(
                        text: 'Custom App',
                      ),
                ),
              ),
              Container(
                margin: EdgeInsets.symmetric(vertical: 40.0),
                child: Text(
                  "Settings",
                  style: Theme.of(context).textTheme.title,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

给定代码的输出

我正在寻找的设计

我尝试过使用 Center 小部件,但它没有使 ListView 居中

I have tried using the Center widget but it does not center the ListView

推荐答案

ListView 填满了整个 Expanded Widget,这就是为什么使用 Center 小部件不起作用,所以应该添加 shr​​inkWrap: true所以 ListView 只需要它的孩子的高度.

The ListView fills the entire Expanded Widget, that's why using the Center widget didn't work, so shrinkWrap: true should be added so the ListView takes only the height of it's children.

在浏览了我找到的关于灵活小部件的文档后

After skimming through the documentation I found about Flexible Widget

Flexible, which does not force the child to fill the available space.

做出改变并像魅力一样工作

Made the change and works like a charm

Flexible(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: 4,
                  itemBuilder: (BuildContext context, int index) =>
                      CustomAppText(
                        text: 'Custom App',
                      ),
                ),
              ),

这篇关于在 Column Flutter 中居中展开 ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆