如何让变量仅本地作用于Stateless Widget而非全局(Flutter)
解决方案:单独隐藏点击的按钮
核心思路是用**集合(Set)**替代单个布尔变量,记录需要隐藏的按钮文本,让每个按钮根据自身文本判断是否显示,同时保持ButtonTest和ButtonsList为无状态组件:
修改后的完整代码
class TestTest extends Stateful Widget { const TestTest({Key? key}) : super(key: key); @override State<TestTest> createState() => _TestTestState(); } class _TestTestState extends State<TestTest> { // 用集合记录已点击需要隐藏的按钮文本 Set<String> hiddenButtons = {}; String text = ''; @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ SizedBox(height: 50), ButtonsList( onTap: (val) { setState(() { text = val; print(text); // 点击时将当前按钮文本加入隐藏集合 hiddenButtons.add(val); }); }, hiddenButtons: hiddenButtons, ), ], ), ); } } class ButtonsList extends Stateless Widget { const ButtonsList({ super.key, required this.onTap, required this.hiddenButtons, }); final ValueChanged<String>? onTap; final Set<String> hiddenButtons; @override Widget build(BuildContext context) { return Column( children: [ Faction(FactionText: 'Options:'), SizedBox(height: 10), ButtonTest( text: 'option A', onTap: onTap, isHidden: hiddenButtons.contains('option A'), ), SizedBox(height: 10), ButtonTest( text: 'option B', onTap: onTap, isHidden: hiddenButtons.contains('option B'), ), SizedBox(height: 10), ButtonTest( text: 'option C', onTap: onTap, isHidden: hiddenButtons.contains('option C'), ), SizedBox(height: 10), ButtonTest( text: 'option D', onTap: onTap, isHidden: hiddenButtons.contains('option D'), ), SizedBox(height: 10), ButtonTest( text: 'option E', onTap: onTap, isHidden: hiddenButtons.contains('option E'), ), SizedBox(height: 10), ButtonTest( text: 'option F', onTap: onTap, isHidden: hiddenButtons.contains('option F'), ), SizedBox(height: 10), ], ); } } class ButtonTest extends Stateless Widget { const ButtonTest({ super.key, required this.text, required this.onTap, required this.isHidden, }); final String text; final ValueChanged<String>? onTap; // 接收是否隐藏的状态,由外部判断后传入 final bool isHidden; @override Widget build(BuildContext context) { return Visibility( // 隐藏状态取反,isHidden为true时不显示 visible: !isHidden, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.blueGrey, ), child: ListTile( onTap: () { onTap?.call(text); }, title: Text( text, style: TextStyle( fontSize: 15, fontFamily: 'SourceSansPro', fontWeight: FontWeight.bold, ), ), ), ), ); } }
关键修改说明
- 主组件用
Set<String> hiddenButtons替代单个bool isChecked,集合自动去重,能准确记录所有已点击的按钮文本 onTap回调中,点击按钮时将对应文本添加到hiddenButtons集合,触发状态更新ButtonsList新增hiddenButtons参数,传递给每个ButtonTest,并为每个按钮判断是否在隐藏集合中ButtonTest接收isHidden参数,通过!isHidden控制自身可见性,实现单个按钮独立隐藏- 全程保持
ButtonTest和ButtonsList为无状态组件,所有状态由主StatefulWidget统一管理
内容的提问来源于stack exchange,提问作者Nomad09
相关产品推荐
相关产品推荐

