Flutter中StatelessWidget下TextField的onChanged赋值返回null问题
解决TextField输入值无法赋值给变量(始终返回null)的问题
核心错误分析
你代码里的onChanged回调赋值逻辑完全颠倒了:
onChanged: (newText) { newText = newTaskTitle!; // 错误:把初始为null的newTaskTitle赋值给newText,而非将输入值存入newTaskTitle },
这直接导致newTaskTitle始终保持初始的null状态,根本没接收到用户的输入内容。
解决方案1:修正onChanged赋值逻辑
调整赋值方向,将用户输入的newText赋值给newTaskTitle:
TextField( // 其他属性保持不变 onChanged: (newText) { newTaskTitle = newText; // 正确:将输入内容存入目标变量 }, ),
解决方案2:使用TextEditingController(StatelessWidget更推荐的方式)
对于StatelessWidget,用TextEditingController管理输入文本更规范,能避免组件重建时变量重置的潜在问题:
class AddTaskScreen extends StatelessWidget { const AddTaskScreen({Key? key}) : super(key: key); // 定义输入控制器 final TextEditingController _taskController = TextEditingController(); @override Widget build(BuildContext context) { return Container( color: Colors.black, child: Container( padding: const EdgeInsets.all(20), decoration: const BoxDecoration( color: Color(0xff1f1f1f), borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20)), ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Text( 'Add a task', textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontSize: 20), ), TextField( controller: _taskController, // 绑定控制器 cursorColor: Colors.white38, decoration: const InputDecoration( enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.white38), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.white38), ), ), textAlign: TextAlign.center, autofocus: true, ), TextButton( style: ButtonStyle( backgroundColor: MaterialStateColor.resolveWith( (states) => Colors.white.withOpacity(0.9)), overlayColor: MaterialStateColor.resolveWith((states) => Colors.white), ), onPressed: () { String? newTaskTitle = _taskController.text.isEmpty ? null : _taskController.text; if (newTaskTitle == null) { Navigator.pop(context); print('null'); } else { Provider.of<TaskData>(context, listen: false).addTask(newTaskTitle); Navigator.pop(context); } }, child: const Text( 'Add', style: TextStyle( fontSize: 15, fontWeight: FontWeight.bold, color: Colors.black, ), ), ), ], ), ), ); } }
注:调用Provider.of时添加listen: false,避免在StatelessWidget中触发不必要的状态监听警告。
内容的提问来源于stack exchange,提问作者Bryar Laiq
相关产品推荐
相关产品推荐

