Flutter:如何设置列表Tile的默认选中高亮状态?
实现ListView.builder中指定Tile默认高亮的解决方案
要让指定Tile默认高亮,核心是给selectedIndex设置初始默认值,具体分两种场景处理:
1. 固定默认选中某一个(比如第一个)
直接在声明selectedIndex时赋值目标索引:
// 在State类中声明变量时直接初始化 int selectedIndex = 0; // 默认选中第一个Tile
2. 根据已有选中状态匹配索引(比如从widget.food.selectedVar反推)
如果你的widget.food已经有默认选中的selectedVar,可以在initState里找到对应的索引:
late int selectedIndex; @override void initState() { super.initState(); // 找到与selectedVar匹配的索引,没找到则默认选第一个 selectedIndex = widget.food.variations.indexWhere( (variation) => variation == widget.food.selectedVar, orElse: () => 0, ); }
优化冗余的点击逻辑(可选)
你当前onTap里的判断完全冗余,不管什么情况都会设置selectedIndex = index,可以简化成:
onTap: () { setState(() { selectedIndex = index; widget.food.selectedVar = widget.food.variations[index]; }); },
修改后的完整代码示例
SizedBox( height: 100, child: ListView.builder( itemCount: widget.food.variations.length, scrollDirection: Axis.horizontal, itemBuilder: (context, index) => GestureDetector( onTap: () { setState(() { selectedIndex = index; widget.food.selectedVar = widget.food.variations[index]; }); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: selectedIndex == index ? kPrimaryColor : Colors.white, borderRadius: BorderRadius.circular(40), ), child: Column( children: [ Image.asset( widget.food.variations[index].imgURL.toString(), width: 52, ), Text( widget.food.variations[index].title, ), ], ), ), ), ), ), ),
内容的提问来源于stack exchange,提问作者shimomaru
相关产品推荐
相关产品推荐

