Flutter 如何使用GridView优化代码实现4x4网格布局
问题描述
我想要使用GridView整理现有代码(我认为这是该场景下的最优方案),但实际使用时遇到了问题。我有16个results变量,命名依次为result1、result2……result16,希望将它们按照4x4的形式排列,如下图所示:
现有代码片段
child: RichText( text: TextSpan( children: [ TextSpan( text: widget.result1 + ' ', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: checkdominantA(widget.predominant, widget.result1), height: 2.5, letterSpacing: 0.7, ), // ... TextSpan( text: widget.result16 + ' ', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: checkdominantA(widget.predominant, widget.result16), height: 2.5, letterSpacing: 0.7, ), ), ), ], ), ),
实现方案
使用GridView.count可以快速实现固定列数的网格布局,无需重复编写16个样式相同的组件,后续维护也更方便。
第一步先将16个result变量整合为一个列表:
List<String> resultList = [ widget.result1, widget.result2, widget.result3, widget.result4, widget.result5, widget.result6, widget.result7, widget.result8, widget.result9, widget.result10, widget.result11, widget.result12, widget.result13, widget.result14, widget.result15, widget.result16, ];
第二步替换原有RichText组件为GridView:
child: GridView.count( // 不需要GridView单独滚动可开启以下配置 physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, // 配置4列,实现4x4布局 crossAxisCount: 4, // 可自定义格子宽高比,1为正方形 childAspectRatio: 1, children: List.generate(16, (index) => Center( child: Text( '${resultList[index]} ', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: checkdominantA(widget.predominant, resultList[index]), height: 2.5, letterSpacing: 0.7, ), ), )), )
如果有需要保留RichText的相关特性,只需要将上述代码中Text组件替换为对应的RichText即可,遍历逻辑完全一致。
内容的提问来源于stack exchange,提问作者bilbo_bo
相关产品推荐
相关产品推荐

