Flutter Card Swiper组件点击浮动按钮触发滑动无响应问题
问题分析与解决方案
问题出在CardSwiper控制器实例不匹配:你在CardSwiper组件内部直接创建了CardSwiperController(),而FloatingActionButton里调用的controller是另一个未和组件绑定的实例,两者毫无关联,所以调用swipe方法自然不会触发卡片滑动。
修复步骤
- 在你的State类中声明全局的
CardSwiperController实例:
late CardSwiperController controller; @override void initState() { super.initState(); controller = CardSwiperController(); }
- 将这个全局控制器传递给
CardSwiper的controller参数,替换原来的局部创建:
Flexible( child: CardSwiper( controller: controller, // 这里用全局实例 cardsCount: flip_cards.length, onSwipe: _onswip, onUndo: _onUndo, isLoop: false, numberOfCardsDisplayed: 3, cardBuilder: ( context, index, horizontalThresholdPercentage, verticalThresholdPercentage, ) => flip_cards[index], ), ),
- 保持FloatingActionButton的逻辑不变,此时调用的就是和组件绑定的控制器:
FloatingActionButton( onPressed: () { controller.swipe(CardSwiperDirection.right); }, child: const Icon( Icons.thumb_up, color: Colors.green, size: 80.0, ), ),
额外说明
你之前尝试的setState()和替换按钮类型,都没有触及核心问题——控制器实例未绑定,所以这些操作无法解决问题。只要保证组件和按钮使用同一个CardSwiperController实例,就能正常触发滑动。
内容的提问来源于stack exchange,提问作者علي المرتضى الشامي
相关产品推荐
相关产品推荐

