TextField foucus上,我想选择所有文本,以便在用户开始键入时删除现有文本。

这将替代Android中的android:selectAllOnFocus="true"

如何做到这一点?

最佳答案

显式传递一个 Controller 和focusNode,则您具有完全控制权:

final _controller = TextEditingController();
final _focusNode = FocusNode();

initState() {
  super.initState();
  _focusNode.addListener(() {
    if(_focusNode.hasFocus) {
      _controller.selection = TextSelection(baseOffset: 0, extentOffset: _controller.text.length);
    }
  });
}

build() => TextField(controller: _controller, focusNode: _focusNode);

更新
https://github.com/flutter/flutter/issues/28307#issuecomment-467952074来防止无限循环:
_controller.addListener(() {
  final newText = _controller.text.toLowerCase();
  _controller.value = _controller.value.copyWith(
    text: newText,
    selection: TextSelection(baseOffset: newText.length, extentOffset: newText.length),
    composing: TextRange.empty,
  );
});

08-18 17:49