Flutter中使用builder方法构建SwitchListTile时开关无法正常工作
问题根因
封装的构建方法存在3处错误,直接导致开关状态无法正常更新:
- 变量名拼写不一致:方法入参声明为
descreption,组件内部调用时写的是description,名称不匹配会直接触发编译错误 - 状态值透传丢失:
SwitchListTile的onChanged回调会自动返回开关切换后的最新布尔值,但原有写法onChanged: (_) => updateValue()直接丢弃了该参数,导致setState时拿不到新的状态值 - 类型定义模糊:入参
curValue、updateValue都用var/通用Function声明,没有指定明确的类型约束,容易引发隐式类型错误
修复代码
首先修正_buildSwitch方法的实现:
Widget _buildSwitch( String title, String description, bool curValue, ValueChanged<bool> updateValue, ) { return SwitchListTile( value: curValue, onChanged: updateValue, title: Text(title), subtitle: Text(description), ); }
修复后直接复用该方法生成所有筛选开关即可,无麸质选项的原有调用逻辑不需要修改,其余无乳糖、纯素、素食选项按照相同格式传入对应状态变量和更新逻辑即可正常工作。
完整可运行的修复后页面代码参考:
import 'package:flutter/material.dart'; class FilterPage extends StatefulWidget { static const route = '/filter-page'; @override State<FilterPage> createState() => _FilterPageState(); } class _FilterPageState extends State<FilterPage> { bool _glutenFree = false; bool _lactoseFree = false; bool _vegan = false; bool _vegetarian = false; Widget _buildSwitch( String title, String description, bool curValue, ValueChanged<bool> updateValue, ) { return SwitchListTile( value: curValue, onChanged: updateValue, title: Text(title), subtitle: Text(description), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Filter settings'), ), // 替换为你自己实现的DrawerWidget即可 // drawer: DrawerWidget(), body: Column( children: [ const Padding( padding: EdgeInsets.all(20), child: Text( 'Adjust your meal selection', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), ), Expanded( child: ListView( children: [ _buildSwitch( 'Gluten-Free', 'Only include gluten-free meals', _glutenFree, (newValue) { setState(() { _glutenFree = newValue; }); }, ), _buildSwitch( 'Lactose-Free', 'Only include lactose-free meals', _lactoseFree, (newValue) { setState(() { _lactoseFree = newValue; }); }, ), _buildSwitch( 'Vegan', 'Only include vegan meals', _vegan, (newValue) { setState(() { _vegan = newValue; }); }, ), _buildSwitch( 'Vegetarian', 'Only include vegetarian meals', _vegetarian, (newValue) { setState(() { _vegetarian = newValue; }); }, ), ], ), ) ], ), ); } }
内容的提问来源于stack exchange,提问作者Smit Prajapati
相关产品推荐
相关产品推荐

