Flutter GridView 删除所有 Children 相同大小的额外间距

Flutter GridView Remove Extra Spacing with all Children of same size

我是 Flutter 的新手,正在自学。我只想显示包含任何其他小部件的 4 个块的网格。但问题是我需要显示 4 个大小相等的网格 children。喜欢 11 22

我是这样做的:

         Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(
                height: 20,
              ),
              Expanded(
                child: GridView(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  padding: EdgeInsets.zero,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 1, crossAxisSpacing: 0, mainAxisSpacing: 0),
                  children: [
                    FittedBox(child: Container(color:Colors.deepOrangeAccent,child: Text("Hello"),),fit: BoxFit.fill),
                    FittedBox(child: Container(color:Colors.blue,child: Text("Hello")),fit: BoxFit.fill,),
                    FittedBox(child: Container(color:Colors.cyanAccent,child: Text("Hello")),fit: BoxFit.fill,),
                    FittedBox(child: Container(color:Colors.deepOrangeAccent,child: Text("Hello")),fit: BoxFit.fill,)
                  ],
                ),
              )
            ],
          )

我的截图:

如果我理解你的问题,你想将屏幕分成 4 个相等的部分。您肯定可以使用 GridView 做到这一点,但 GridView 不会帮助您分配可用 space.

您需要在列中使用行,并利用每个视图的扩展小部件。您可以查看下面的示例代码:

您也可以 运行 此代码 dartpad.dev


class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: Row(
            children: [
              Expanded(
                child: Container(color: Colors.red),
              ),
              Expanded(
                child: Container(color: Colors.blue),
              ),
            ],
          ),
        ),
        Expanded(
          child: Row(
            children:  [
              Expanded(
                child: Container(color: Colors.green),
              ),
              Expanded(
                child: Container(color: Colors.yellow),
              ),
            ],
          ),
        )
      ],
    );
  }
}

它将为您提供以下输出。

到目前为止我自己发现的是提供:

 childAspectRatio: MediaQuery.of(context).size.width / (MediaQuery.of(context).size.height / 1),

通过这样做,屏幕完美地分成 4 个网格块,请参见下面的屏幕截图: