简体   繁体   English

扑。 - 如何在 Gridview 中动态 crossAxisCount

[英]Flutter. - How to have dynamic crossAxisCount in Gridview

I have a GridView where I want the crossAxisCount to change based on the device size specifically mobile (crossAxisCount:3) and tablet (crossAxisCount:4).我有一个 GridView,我希望 crossAxisCount 根据设备大小特别是移动设备 (crossAxisCount:3) 和平板电脑 (crossAxisCount:4) 进行更改。 I am new to Flutter and I know there is MediaQuery but I don't know how to use it.我是 Flutter 的新手,我知道有 MediaQuery,但我不知道如何使用它。

I am also attaching an image for reference.我还附上了一张图片以供参考。 What I am looking for.我在寻找什么。

you can check if the device's shortest side < 600 so it's phone您可以检查设备的最短边是否 < 600 所以它是电话

crossAxisCount: MediaQuery.of(context).size.shortestSide < 600 ? 2 : 4,

as an option you can create extension for BuildContext like this作为一个选项,您可以像这样为 BuildContext 创建扩展

extension ContextExtension on BuildContext {
  bool get isTablet => MediaQuery.of(this).size.shortestSide > 600;

  bool get isPhone => MediaQuery.of(this).size.shortestSide < 600;
}

and use it:并使用它:

crossAxisCount: context.isTablet ? 4 : 2

you can use wrap widget instead of gridview A Wrap lays out each child and attempts to place the child adjacent to the previous child in the main axis, given by direction, leaving spacing space in between.您可以使用 wrap 小部件而不是 gridview you can learn how to use wrap widget in this article: https://medium.com/flutter-community/flutter-wrap-widget-e1ee0b005b16您可以在本文中了解如何使用 wrap 小部件: https : //medium.com/flutter-community/flutter-wrap-widget-e1ee0b005b16

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM