Flutter Grid Layout-GridView

  dart, flutter, Front end, modularization, ui


1. Preface

FlutterAs one of the most popular technologies at present, it has already attracted the attention of a large number of technology lovers, even some, due to its excellent performance and smooth multi-terminal differences.Idle fish,meituan,TencentSuch large companies have been put into production. Although its ecology is not fully mature at present, it depends on what is behind it.GoogleBlessing, its development speed has been amazing enough to predict the futureFlutterThe demand for developers will also grow.

It has been 9102 years for the sake of the current technology taste and the future trend. As a front-end developer, there seems to be no reason not to try it. It is with this mentality that the author also began to learnFlutterAt the same time, we have built a trainingWarehouse, all subsequent code will be hosted on it, welcome star, learn together. This is my Flutter series:

afterLast articleYesListViewIn the study of components, we have already got a preliminary understanding of the use of rolling components, which is what we have to learn today.GridViewComponents are very helpful. Because both inherit fromBoxScrollViewTherefore, more than 80% of their properties are the same and their usage is very similar.

As can be seen from the following figure,GridViewGrid layout is actually used very frequently in app, so let’s take a look atFlutterHow to use it in ~


2. First meeting GridView

Our hero todayGridViewThere are five constructors:GridView,GridView.builder,GridView.count,GridView.extentAndGridView.custom. But don’t panic, because it can be said that you will have mastered its default constructor ~

Let’s take a lookGridViewConstructor (infrequent attributes omitted):

  Key key,
  Axis scrollDirection = Axis.vertical,
  bool reverse = false,
  ScrollController controller,
  ScrollPhysics physics,
  bool shrinkWrap = false,
  EdgeInsetsGeometry padding,
  @required this.gridDelegate,
  double cacheExtent,
  List<Widget> children = const <Widget>[],

Although it is a lot of attributes, but most of them are very familiar with, old friends ~ except a required parametergridDelegateOutside, all andListViewThe parameters of the default constructor are the same, which is why the beginning of the article says that you have mastered them.ListViewLearn againGridViewA very easy reason.

So next, let’s focus ongridDelegateThis parameter, it is actuallyGridViewHow the component controls a delegate that arranges child elements. We can trace the source code atscroll_view.dartAs you can see in,gridDelegateThe type of isSliverGridDelegate, further tracking intosliver_grid.dartYou can see.SliverGridDelegateIn fact, it is an abstract class, and there are two implementation classes:

  • SliverGridDelegateWithFixedCrossAxisCount: used for scenes with a fixed number of columns;
  • SliverGridDelegateWithMaxCrossAxisExtent: Used for scenes where child elements have a maximum width limit;

2.1 SliverGridDelegateWithFixedCrossAxisCount

Let’s take a look firstSliverGridDelegateWithFixedCrossAxisCountAccording to the class name, we can also guess what it is for: if your layoutThe number of columns in each row is fixedThen you should use it.

Let’s look at its constructor:

  @required this.crossAxisCount,
  this.mainAxisSpacing = 0.0,
  this.crossAxisSpacing = 0.0,
  this.childAspectRatio = 1.0,
  • crossAxisCount: Number of columns, i.e. a row has several sub-elements;
  • mainAxisSpacing: gap spacing in the main axis direction;
  • crossAxisSpacing: gap spacing in the minor axis direction;
  • childAspectRatio: Ratio of width to height of child elements.


I think you will understand the meaning of each parameter in seconds when you see the above example diagram. However, there is one point that requires special attention:If the aspect ratio of your child element is not 1, then you must set itchildAspectRatioAttribute.

2.2 SliverGridDelegateWithMaxCrossAxisExtent

SliverGridDelegateWithMaxCrossAxisExtentIn actual application, it may be relatively few. Let’s look at its constructor:

  @required this.maxCrossAxisExtent,
  this.mainAxisSpacing = 0.0,
  this.crossAxisSpacing = 0.0,
  this.childAspectRatio = 1.0,

It can be seen that besidesmaxCrossAxisExtentIn addition, other parameters andSliverGridDelegateWithFixedCrossAxisCountThat makes no difference. ThenmaxCrossAxisExtentWhat does it do? Let’s look at an example:

If the mobile phone screen is wide375,crossAxisSpacingThe value is0,

  • maxCrossAxisExtentThe value is125, the number of grid columns will be3. Because ..125 * 3 = 375, just, the width of each column is375/3.
  • maxCrossAxisExtentThe value is126, the number of grid columns will be3. Because ..126 * 3 > 375The width of each column will be375/3.
  • maxCrossAxisExtentThe value is124, the number of grid columns will be4. Because ..124 * 3 < 375The width of each column will be375/4.

As you can see,maxCrossAxisExtentIn fact is to tellGridViewWhat is the maximum width of component sub-elements and then calculate the appropriate column width (in fact, we seldom use this method, so the frequency of this method is not high).

3. Practical application

After the previous introduction, we have already made some comments onGrdiViewWith a preliminary understanding of the components, let’s look at how to use them. Remember beforeGridViewAll kinds of constructors of? In fact:

  1. GridViewThe default constructor can be analogous toListViewDefault constructor forFinite number of subelementsThe scene, becauseGridViewComponents are rendered all at oncechildrenThe child element component in;
  2. GridView.builderThe constructor can be analogous toListView.builderConstructor forLong listThe scene, becauseGridViewComponents will dynamically create and destroy sub-elements according to whether they appear on the screen, reducing memory consumption and rendering more efficiently.
  3. GridView.countThe constructor isGrdiViewUseSliverGridDelegateWithFixedCrossAxisCountThe shorthand for “grammar sugar” has exactly the same effect.
  4. GridView.extentConstructor formulaGridViewUseSliverGridDelegateWithMaxCrossAxisExtentThe effect is exactly the same.

Let’s look at a simple example, which usesGridView.countThe constructor imitates the service list of the take-out home page (the code of the service menu item can be seenHere, is also a further consolidation of the use of basic components):

Code (File address)

  crossAxisCount: 5,
  padding: EdgeInsets.symmetric(vertical: 0),
  children: serviceList.map((item) => ServiceItem(data: item)).toList(),

/* 完全等同于 */

  padding: EdgeInsets.symmetric(vertical: 0),
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 5,
  children: serviceList.map((item) => ServiceItem(data: item)).toList(),



Let’s look at a list that imitates cross talk in HimalayasGridView.builderSpecific examples of creating grid layout (the code of crosstalk cards can be seenHere):

Code (File address)

  shrinkWrap: true,
  itemCount: programmeList.length,
  physics: NeverScrollableScrollPhysics(),
  padding: EdgeInsets.symmetric(horizontal: 16),
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 3,
    mainAxisSpacing: 10,
    crossAxisSpacing: 10,
    childAspectRatio: 0.7,
  itemBuilder: (context, index) {
    return Programme(data: programmeList[index]);



4. Summary

This article first introducedGridViewComponent’s attribute meaning, and focuses on the explanationSliverGridDelegateWithFixedCrossAxisCountAndSliverGridDelegateWithMaxCrossAxisExtentRespectively applicable application scenarios. Then, two practical application examples are introducedGridViewMethods of using constructors commonly used by components. I hope that through the introduction of this article, you can masterFlutterUse of Medium Grid Layout ~

All code in this article is managed inHere, can also pay attention to myBlog, welcome to exchange learning ~