Flutter开发:如何为GridView每个网格单元设置不同颜色?
方案1:在现有map遍历逻辑中直接获取索引
Dart的List类型自带asMap()方法,可将列表转换为「键为元素索引、值为列表元素」的Map对象,无需自行维护全局counter变量,避免多次重绘时counter累加导致的颜色逻辑错误:
GridView.count( padding: EdgeInsets.only(top: 0), physics: BouncingScrollPhysics(), childAspectRatio: getProportionateScreenWidth(159) / getProportionateScreenWidth(115), crossAxisCount: 2, crossAxisSpacing: getProportionateScreenWidth(28.5), mainAxisSpacing: getProportionateScreenWidth(14.3), children: controller.letters.asMap().entries.map( (entry) { int index = entry.key; // 直接获取当前元素索引 String e = entry.value; // 可自定义颜色规则,比如奇偶变色、从预定义颜色列表取色 Color textColor = index % 2 == 0 ? Color(0xff6FC989) : Color(0xff00A49A); // 如果需要更多颜色,可提前定义颜色列表: // List<Color> colorPool = [Color(0xff6FC989), Color(0xff00A49A), Color(0xffF2994A)...]; // 取值:textColor = colorPool[index % colorPool.length]; return Material( elevation: 3, borderRadius: BorderRadius.circular( getProportionateScreenWidth(33)), child: Container( height: getProportionateScreenWidth(115), width: getProportionateScreenWidth(159), decoration: BoxDecoration( borderRadius: BorderRadius.circular( getProportionateScreenWidth(33)), ), child: Center( child: Text( e, style: TextStyle( fontSize: getProportionateScreenWidth(54), fontWeight: FontWeight.bold, color: textColor ) )), ), ); }, ).toList(), ),
方案2:使用GridView.builder实现(更推荐动态数据场景)
如果数据是从接口动态获取的,使用GridView.builder性能更好,且自带的itemBuilder参数直接提供索引参数,无需额外转换:
GridView.builder( padding: EdgeInsets.only(top: 0), physics: BouncingScrollPhysics(), itemCount: controller.letters.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: getProportionateScreenWidth(159) / getProportionateScreenWidth(115), crossAxisSpacing: getProportionateScreenWidth(28.5), mainAxisSpacing: getProportionateScreenWidth(14.3), ), itemBuilder: (context, index) { String e = controller.letters[index]; Color textColor = index % 2 == 0 ? Color(0xff6FC989) : Color(0xff00A49A); return Material( elevation: 3, borderRadius: BorderRadius.circular(getProportionateScreenWidth(33)), child: Container( height: getProportionateScreenWidth(115), width: getProportionateScreenWidth(159), decoration: BoxDecoration( borderRadius: BorderRadius.circular(getProportionateScreenWidth(33)), ), child: Center( child: Text( e, style: TextStyle( fontSize: getProportionateScreenWidth(54), fontWeight: FontWeight.bold, color: textColor ), ) ), ), ); } )
内容的提问来源于stack exchange,提问作者DieabeS
相关产品推荐
相关产品推荐

