Flutter新手开发待办应用:使用TextField获取用户输入后点击按钮文本不更新的问题排查
解决你的Flutter待办应用输入不更新问题
嘿,我一眼就看到问题啦!这是新手刚接触Flutter状态管理时很容易踩的小坑,别担心,改起来很简单~
问题根源:变量被build方法反复重置
你把_textController和userInput这两个关键变量放在了build方法内部:
@override Widget build(BuildContext context) { final _textController = TextEditingController(); // 这里! String userInput = ""; // 还有这里! // ... 其他代码 }
Flutter的setState会触发build方法重新执行,每次执行build,这两个变量都会被重新初始化——你点击按钮刚把userInput设为输入框内容,下一秒build又把它变回空字符串了,自然看不到更新后的文本。
修复步骤:把变量移到State类成员位置
把这两个变量移到_LandingPageState类的顶部,作为类的成员变量,这样它们的生命周期就和State实例绑定,不会被每次build重置:
修改后的landing_page.dart代码:
import 'package:flutter/material.dart'; import 'package:flutter_application_1/presentation/widgets/to_do_section.dart'; class LandingPage extends StatefulWidget { const LandingPage({Key? key}) : super(key: key); @override State<LandingPage> createState() => _LandingPageState(); } class _LandingPageState extends State<LandingPage> { // ✅ 把变量移到这里,成为类成员 final _textController = TextEditingController(); String userInput = ""; // ✅ 记得添加dispose方法,销毁控制器避免内存泄漏 @override void dispose() { _textController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Center(child: Text("To-Do-App")), backgroundColor: Colors.redAccent, ), body: SingleChildScrollView( child: Column( children: [ const ToDos(), Column( children: [ Padding( padding: EdgeInsets.only(top: 8.0, left: 20, right: 20, bottom: 20), child: TextField( controller: _textController, textAlign: TextAlign.center, decoration: InputDecoration( border: OutlineInputBorder(), hintText: "Add a new ToDo", ), ), ), MaterialButton( color: Colors.redAccent, onPressed: () { setState(() { userInput = _textController.text; }); }, child: Text("Admit", style: TextStyle(color: Colors.white),), ), Text(userInput) ], )], ), ), ); } }
额外小提示
我还帮你加上了dispose方法,在State销毁时释放TextEditingController的资源,这是个好习惯,能避免不必要的内存泄漏哦。
现在运行代码试试,点击按钮后输入的内容应该就能正常显示啦!
内容的提问来源于stack exchange,提问作者laniakea
相关产品推荐
相关产品推荐

