如何在 Flutter 应用程序中创建响应式网格?

How to create responsive grid in flutter app?

使 Flutter 应用响应最佳实践是什么? 在下面的代码中是一个 StraggeredGridView 具有 硬编码值 .

我应该编写一个根据屏幕尺寸计算值的方法,还是有其他方法可以这样做?

感谢您的帮助!

  StaggeredGridView.count(
    crossAxisCount: 2,
    crossAxisSpacing: 20,
    mainAxisSpacing: 20,
    padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 20),
    //shrinkWrap: true,
    children: <Widget>[
      _buildTile(
          Padding(
              padding: const EdgeInsets.all(20.0),
            child: Column(children: <Widget>[
              Material(
                  color: Color.fromRGBO(123, 228, 193, 0.5),
                  child: Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Image.asset(
                      'assets/siren.png',
                      height: 40,
                    ),
                  )),
              Padding(padding: EdgeInsets.only(bottom: 10.0)),
              Text('NOTRUF', style: tileFontStyle),
            ]),
          ),),

我最近一直在做的是,我在应用程序启动时获取它的尺寸,并将它们存储为我在整个应用程序中使用的常量。查看 this,因为我发现它很有帮助。

您还可以使用一些自己进行缩放的小部件,例如 layoutBuilder 更多 here

layoutBuilder @Abbas.M 提到的是一种可能性你也可以使用 mediaQuery

    var deviceData = MediaQuery.of(context); 
    var screenSize = MediaQuery.of(context).size;
    var deviceOrientation = MediaQuery.of(context).orientation;

    if (screenSize.width > oneColumnLayout) {
      ...
    } else {
      ...
    }

例如设备数据、屏幕尺寸或方向,还有动画和其他真正有用的东西。

使用 responsive_grid

它的工作方式类似于 Bootstrap 网格系统

您可以像在 CSS 中那样使其具有响应性。

运用数学!但是如何?

用布局构建器包装您的小部件并使用 constraints.maxWidth 来玩转 crossAxisCount 属性:

crossAxisCount:(constraints.maxWidth ~/ 250).toInt()

在 crossAxisCount 上使用 MediaQuery.of(context).orientation == Orientation.landscape。然后使用三元运算符或 if/else 语句来声明 crossAxisCount 值。请参见下面的示例。为我工作。

crossAxisCount: (MediaQuery.of(context).orientation == Orientation.landscape) ? 4 : 2