ListTile组件selectedTileColor滚动时仍显示,如何使其隐藏?
解决ListTile滚动时selectedTileColor可见的问题
方法一:通过滚动控制器监听滚动状态,动态切换选中背景色
- 先创建滚动控制器并监听滚动事件:
final ScrollController _scrollController = ScrollController(); bool _isScrolling = false; @override void initState() { super.initState(); _scrollController.addListener(() { setState(() { _isScrolling = _scrollController.position.isScrollingNotifier.value; }); }); } @override void dispose() { _scrollController.dispose(); super.dispose(); } - 在ListTile中根据滚动状态设置
selectedTileColor:ListTile( selected: true, selectedTileColor: _isScrolling ? Colors.transparent : Colors.blue[100], title: const Text('示例列表项'), // 其他属性配置... )
- 先创建滚动控制器并监听滚动事件:
方法二:用NotificationListener包裹列表,实时监听滚动通知
直接在列表外层套滚动通知监听器,动态判断滚动状态:NotificationListener<ScrollNotification>( onNotification: (notification) { setState(() { _isScrolling = notification is ScrollUpdateNotification; }); return false; }, child: ListView.builder( itemCount: 20, itemBuilder: (context, index) { return ListTile( selected: index == _selectedIndex, selectedTileColor: _isScrolling ? Colors.transparent : Colors.blue[100], title: Text('列表项 $index'), onTap: () => setState(() => _selectedIndex = index), ); }, ), )
核心逻辑就是:通过滚动状态变量_isScrolling,在滚动时把selectedTileColor设为透明,停止滚动后恢复原来的选中背景色。如果用的是其他风格的列表组件(比如CupertinoListTile),只需要对应调整控制选中背景的参数即可。
内容的提问来源于stack exchange,提问作者baha
相关产品推荐
相关产品推荐

