如何在Flutter的ListWheelScrollView中添加上下项模糊效果?
解决ListWheelScrollView仅给非中心项添加模糊效果的方案
要实现仅对中心项以外的条目添加模糊,核心思路是通过滚动控制器判断当前条目是否为选中的中心项,仅对非中心项应用ImageFiltered组件。具体实现步骤如下:
1. 确保使用正确的滚动控制器类型
你的scrollController需要是FixedExtentScrollController,这样才能获取当前选中的中心项索引:
final FixedExtentScrollController scrollController = FixedExtentScrollController();
2. 修改条目生成逻辑,根据索引判断是否添加模糊
在遍历dateIdeas时,通过asMap().entries获取每个条目的索引,对比控制器的selectedItemIndex,仅对非中心项包裹ImageFiltered:
ListWheelScrollView.useDelegate( overAndUnderCenterOpacity: 0.2, controller: scrollController, physics: const NeverScrollableScrollPhysics(), itemExtent: 50, perspective: 0.003, diameterRatio: 1.5, childDelegate: ListWheelChildLoopingListDelegate( children: dateIdeas.asMap().entries.map((entry) { final int index = entry.key; final String idea = entry.value; final bool isCenterItem = index == scrollController.selectedItemIndex; return Center( child: isCenterItem ? Text( idea, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ) : ImageFiltered( imageFilter: ImageFilter.blur(sigmaX: 2.0, sigmaY: 2.0), // 可自行调整模糊程度 child: Text( idea, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ), ); }).toList(), ), );
3. 添加滚动监听,实时更新UI
在组件的initState中添加控制器的监听,滚动时触发setState更新模糊状态:
@override void initState() { super.initState(); scrollController.addListener(() { setState(() {}); }); } @override void dispose() { scrollController.dispose(); // 记得销毁控制器避免内存泄漏 super.dispose(); }
原理说明
之前直接给所有Text套ImageFiltered会导致全部条目模糊,现在通过scrollController.selectedItemIndex精准判断中心项,仅对非中心项应用模糊滤镜,同时通过滚动监听确保滚动过程中模糊效果实时跟随中心项变化。
内容的提问来源于stack exchange,提问作者Cameron Rashleigh
相关产品推荐
相关产品推荐

