如何实现Flutter单按钮切换状态同时增减整数计数器?
解决方案
你只需要在按钮的onTap回调里,切换状态的同时根据so1HasBeenPressed01的新值来更新计数器即可:
当按钮按下后变为绿色(so1HasBeenPressed01变为true)时,给secondaryLeftCounter加1;再次按下恢复蓝灰色(so1HasBeenPressed01变为false)时,给secondaryLeftCounter减1。
修改后的完整代码如下:
class _MainPageState extends State<MainPage> { int secondaryLeftCounter = 0; // 需要修改的整数计数器 bool so1HasBeenPressed01 = false; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ClipRRect( borderRadius: BorderRadius.circular(50.0), child: InkWell( onTap: () { setState(() { so1HasBeenPressed01 = !so1HasBeenPressed01; // 根据按钮状态更新计数器 if (so1HasBeenPressed01) { secondaryLeftCounter++; } else { secondaryLeftCounter--; } }); }, child: Container( width: 30.0, height: 30.0, color: so1HasBeenPressed01 ? Colors.green : Colors.blueGrey[900], ), ), ), ], ); } }
核心逻辑就是每次切换按钮状态时,判断当前是激活(绿色)还是未激活(蓝灰色)状态,对应执行计数器的增减操作,这样同一个按钮就能同时完成颜色切换和计数器的双向调整。
内容的提问来源于stack exchange,提问作者Nomad09
相关产品推荐
相关产品推荐

