Flutter教程:如何修改ListView Builder选中项的边框颜色与宽度
实现ListView Builder选中项的边框样式切换
要实现选中索引对应容器的边框颜色和宽度变化,核心是维护一个选中状态的索引,然后在构建每个item时根据当前索引是否为选中状态来动态调整边框样式,具体步骤如下:
1. 维护选中索引状态
从代码里的productController来看你用的是GetX,直接在你的ProductController里添加一个可观察的选中索引变量:
class ProductController extends GetxController { // 保留原有代码... RxInt selectedBrandIndex = (-1).obs; // 初始设为-1,表示未选中任何项 }
2. 点击时更新选中索引
修改GestureDetector的onTap方法,在原有筛选逻辑的基础上更新选中索引:
onTap: () { productController.selectedBrandIndex.value = index; // 更新选中项索引 productController.filterProducts( collection: productController.section.value.docs![brandsIndex!].items![index].name ); print(productController.section.value.docs![brandsIndex!].items![index].name); },
3. 动态设置边框样式
在Container的decoration属性里,根据当前index是否等于选中索引,切换边框的宽度和颜色:
border: Border.all( width: productController.selectedBrandIndex.value == index ? 2 : 1, color: productController.selectedBrandIndex.value == index ? Colors.blue // 可替换成你想要的选中态颜色 : const Color.fromARGB(255, 224, 224, 224), ),
修改后的完整代码
ListView.builder( scrollDirection: Axis.horizontal, itemCount: productController.section.value.docs![brandsIndex!].items!.length - 1, itemBuilder: (BuildContext context, int index) { return GestureDetector( onTap: () { productController.selectedBrandIndex.value = index; // 新增:更新选中索引 productController.filterProducts( collection: productController.section.value.docs![brandsIndex!].items![index].name ); print(productController.section.value.docs![brandsIndex!].items![index].name); }, child: Padding( padding: const EdgeInsets.only(top: 30, bottom: 40), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 6), child: Container( width: 50.0, height: 50.0, decoration: BoxDecoration( color: const Color.fromARGB(255, 252, 252, 252), // 修改:动态切换边框样式 border: Border.all( width: productController.selectedBrandIndex.value == index ? 2 : 1, color: productController.selectedBrandIndex.value == index ? Colors.blue : const Color.fromARGB(255, 224, 224, 224), ), borderRadius: const BorderRadius.all(Radius.circular(15)), image: DecorationImage( image: CachedNetworkImageProvider( productController.section.value .docs![brandsIndex!].items![index].imageUrl .toString() ), ), ), ), ), ), ); }, ),
如果是用StatefulWidget而非GetX,只需要把selectedBrandIndex换成State类里的普通int变量,点击时调用setState更新即可,核心逻辑完全一致。
内容的提问来源于stack exchange,提问作者Divya
相关产品推荐
相关产品推荐

