简体   繁体   中英

Flutter: TextField difference between onEdittingComplete and onSubmitted

I am trying to figure out the difference between onEdittingComplete and onSubmitted , I don't know when the latter should be used since the former can be used to switch focus or to submit the content of the form.

I tried looking into the documentation but there is not much said about the onSubmitted property.

onSubmitted

As the name suggestions, it's called when user finishes editing, eg press "done" or "send" on the keyboard. The callback conveniently passes the value to you, so you can do your business logic with it. At the same time, since Flutter assumes the user is "done", it will hide the on-screen keyboard.

onEditingComplete

This is more of an "FYI" that tells you that the user has finished editing. It is fired before onSubmitted . It does not pass you the value (while you can technically get the value using a controller, that's not the intention here), because you can still handle value-related business logic in onSubmitted . Both events will fire anyway.

The real purpose behind onEditingComplete is that, in the default implementation, Flutter hides the on-screen keyboard when the keyboard action is considered a "completion" action, such as "done", "go", "send", or "search", but does not hide the keyboard if the action is "non-completion", such as "next" or "previous". (The keyboard action can be modified via textInputAction property of the TextField widget.)

If you don't like this behaviour, you should modify it. For example, "send" is considered a "completion action" here, thus in an Instant Messaging (chatting) app, each time user sends a short message, the keyboard will be collapsed, that's not good. But if we override the onEditingComplete callback to an empty function, it will stop the default behaviour and not hide the keyboard. For example:

TextField(
  controller: _controller,
  onSubmitted: (text) {
    sendMessage(text);
    _controller.clear();
  },
  onEditingComplete: () {}, // do not hide keyboard
  textInputAction: TextInputAction.send,
)

Demo:

演示 gif

onSubmitted:

final ValueChanged<String> onSubmitted

It returns the TextField entered value in onSubmitted callback, most of the time its used for next/previous field button of keyboard when using TextInputAction.next and TextInputAction.previous for textInputAction performed.

onEditingComplete:

final VoidCallback onEditingComplete

It's similar to onSubmitted but does not return value inside the callback, instead, it updates the text controller and then we can fetch a value from the controller where ever required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM