Android Studio实现按钮点击抬起/复位交互功能求助
实现按钮点击抬起/复位的方案
不用复杂的多ListView嵌套,用AnimatedContainer结合状态管理就能轻松实现这个交互效果,步骤如下:
核心思路
- 用一个状态变量记录当前选中的按钮索引(
selectedIndex,初始值设为-1表示无选中) - 每个按钮用
AnimatedContainer包裹,通过transform属性控制位移:选中时向上偏移,未选中时回到原位 - 点击按钮时判断:如果当前选中的就是该按钮,就重置选中索引;否则设置为当前按钮的索引
代码示例
import 'package:flutter/material.dart'; void main() => runApp(const ButtonLiftApp()); class ButtonLiftApp extends StatelessWidget { const ButtonLiftApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: ButtonLiftWidget(), ), ), ); } } class ButtonLiftWidget extends StatefulWidget { @override State<ButtonLiftWidget> createState() => _ButtonLiftWidgetState(); } class _ButtonLiftWidgetState extends State<ButtonLiftWidget> { // 记录当前选中的按钮索引,-1表示无选中 int selectedIndex = -1; // 按钮抬起的偏移量,可根据需求调整 final double liftOffset = -20; void toggleButton(int index) { setState(() { if (selectedIndex == index) { // 再次点击已选中的按钮,取消选中 selectedIndex = -1; } else { // 选中当前按钮 selectedIndex = index; } }); } @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: List.generate(4, (index) { return AnimatedContainer( duration: const Duration(milliseconds: 200), curve: Curves.easeInOut, // 通过transform实现向上抬起的效果 transform: Matrix4.translationValues( 0, selectedIndex == index ? liftOffset : 0, 0, ), margin: const EdgeInsets.symmetric(horizontal: 8), child: ElevatedButton( onPressed: () => toggleButton(index), style: ElevatedButton.styleFrom( fixedSize: const Size(80, 80), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), ), child: Text("按钮${index+1}"), ), ); }), ); } }
额外说明
- 如果需要同时支持多个按钮抬起(原需求是单个,若要多个可改成
Set<int>存储选中索引) - 可以调整
liftOffset和动画时长Duration来匹配设计稿的动效 - 按钮的样式(大小、圆角、颜色)可以根据Figma设计直接修改
ElevatedButton.styleFrom里的参数
内容的提问来源于stack exchange,提问作者Noob tv
相关产品推荐
相关产品推荐

