Flutter实现ElevatedButton点击变色及页面跳转后状态切换
需求与问题描述
预期设计效果

当前设计效果

我需要实现以下功能:点击ElevatedButton时切换颜色,同时跳转到对应页面;比如点击Profile按钮时按钮变色,进入其他页面后该按钮恢复为白色。
以下是我的代码:
ElevatedButton( style: ButtonStyle( padding: MaterialStateProperty.all( EdgeInsets.fromLTRB(30, 20, 30, 20), ), // overlayColor: MaterialStateProperty.all(Colors.red), backgroundColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) return Colors.blue; return Color.fromARGB(255, 0, 79, 143); } ), ), onPressed: () {}, child: new Text( 'Profile', style: TextStyle( fontSize: 16, fontWeight: FontWeight.normal ) ), ),
实现方案
要实现按钮点击跳转时变色、切换页面后恢复原色的效果,核心是通过页面状态标识控制按钮样式,具体实现步骤如下:
- 用变量记录当前活跃页面的标识,比如
currentPage,初始值设为非目标页面的标识。 - 按钮背景色不再仅依赖点击状态,而是根据
currentPage是否为目标页面动态设置。 - 点击按钮时更新活跃页面标识,执行跳转;从目标页面返回或进入其他页面时,重置标识恢复按钮原色。
示例代码
// 假设在StatefulWidget中管理状态 String currentPage = "home"; // 初始为首页 ElevatedButton( style: ButtonStyle( padding: MaterialStateProperty.all( EdgeInsets.fromLTRB(30, 20, 30, 20), ), backgroundColor: MaterialStateProperty.all( currentPage == "profile" ? Colors.blue : Color.fromARGB(255, 0, 79, 143), ), ), onPressed: () { // 更新当前页面标识 setState(() { currentPage = "profile"; }); // 执行页面跳转 Navigator.push( context, MaterialPageRoute(builder: (context) => ProfilePage()), ).then((_) { // 从Profile页面返回时重置状态 setState(() { currentPage = "home"; }); }); }, child: Text( 'Profile', style: TextStyle( fontSize: 16, fontWeight: FontWeight.normal ) ), ),
补充说明
- 如果使用GoRouter等路由管理工具,可以监听路由变化自动更新
currentPage,确保切换到任意非目标页面时按钮都能恢复原色。 - 若存在多个同类导航按钮,可将
currentPage与导航栏索引绑定,统一管理所有按钮的激活状态。
内容的提问来源于stack exchange,提问作者John Reaper
相关产品推荐
相关产品推荐

