You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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: Since initState only 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 updateTitle and updateDescription methods are updating the note object 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:51:05