首页 > 解决方案 > Flutter GridView item wrap_content 高度

问题描述

我是一名 android 开发人员,并且是 Flutter 的新手。

我想创建一个项目高度(我在屏幕截图GridView中用wrap content钢笔绘制它)。但我尝试过使用以下代码,它只给了我方形网格项。我想如何获得高度环绕内容网格项目,但我不知道也找不到如何获得它。请帮忙。谢谢你。

在此处输入图像描述

class CategoryItem extends StatelessWidget {
  final Category category;
  CategoryItem({Key key, @required this.category})
      : assert(category != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Text(
        category.name,
        style: TextStyle(fontSize: 34.0, fontWeight: FontWeight.bold),
      ),
      color: Colors.amberAccent,
    );
  }
}


class CategoryGrid extends StatefulWidget {

  final List<Category> items;

  const CategoryGrid({Key key, this.items}) : super(key: key);

  @override
  _CategoryGridState createState() => _CategoryGridState();
}

class _CategoryGridState extends State<CategoryGrid> {

  @override
  Widget build(BuildContext context) {
    final Orientation orientation = MediaQuery.of(context).orientation;
    return Column(
      children: <Widget>[
        Expanded(
          child: SafeArea(
            top: false,
            bottom: false,
            child: GridView.builder(
              itemCount: widget.items.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: (orientation == Orientation.portrait) ? 2 : 3,),
              itemBuilder: (BuildContext context, int index) {
                return CategoryItem(category: widget.items[index],);
              },
            ),
          ),
        ),
      ],
    );
  }
}

标签: flutterflutter-gridview

解决方案


对于高度,您可以使用“childAspectRatio”

例如-

GridView.count(
    childAspectRatio: 4.0,
    crossAxisCount: 2,

    padding: EdgeInsets.all(5.0),
    children: <Widget>[
        Container(
            margin: EdgeInsets.only(left: 10.0, right: 10.0, top: 5.0),
            child: Text(
                '10:00 AM - 12:00 PM',
                style: new TextStyle( color: Colors.black87, fontSize: 14.0, 
                    fontWeight: FontWeight.normal,
                ),
            ), 
        );
    ],
    shrinkWrap: true,
    // todo comment this out and check the result
    physics: ClampingScrollPhysics(),
)

推荐阅读