Flutter切换焦点时TextFormField丢失输入值问题求助
Hey there! Let's figure out why your TextFormField text keeps clearing when it loses focus.
The issue here is super common for Flutter newbies—you're setting your TextEditingController's text inside the build method. Every time your widget rebuilds (which happens when focus changes, you call setState, or even when the screen rotates), the build method runs again. That means you're overwriting whatever the user typed with the original note.title and note.description values every time the first field loses focus. If those original values were empty, that's exactly why your input disappears!
Here's how to fix it step by step:
Move controller initialization to
initState: SinceinitStateonly runs once when your widget is first created, this ensures you set the initial values just one time, not on every rebuild.
First, make sure your widget is a StatefulWidget (which it looks like it is), then add this method:@override void initState() { super.initState(); // Set initial values only once here titleController.text = note.title; descriptionController.text = note.description; }Delete the controller assignments in
build: Get rid of these two lines from your build method—they're the main culprit!// Remove these lines completely! titleController.text=note.title; descriptionController.text=note.description;Double-check your update logic: Make sure your
updateTitleandupdateDescriptionmethods are updating thenoteobject with the controller's text, not the other way around. They should look like this:void updateTitle() { note.title = titleController.text; } void updateDescription() { note.description = descriptionController.text; }
Quick Tip for Future Projects
The build method should always be a pure function—no side effects like modifying controllers or making API calls. Save all initialization and one-time setup for initState, and use setState only when you need to trigger a rebuild with new state values.
内容的提问来源于stack exchange,提问作者Chirag Patel

