【问题标题】:Why is my Textfield cursor shows on start position of existing Text when refocus为什么重新聚焦时我的文本字段光标显示在现有文本的开始位置
【发布时间】:2021-09-04 01:35:31
【问题描述】:

当我重新编辑我的 TextField 时,为什么光标会显示在现有文本的开头,而不是用户点击的位置。当您取消焦点文本字段然后重新聚焦它时会发生这种情况。

示例代码:

class Mypage extends StatelessWidget {
  const Mypage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: TextEditingController()..text = 'Existing Text Here',
            ),
            TextButton(
                onPressed: () {
                  FocusScope.of(context).unfocus();
                },
                child: Text('Unfocus'))
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter flutter-layout flutter-textinputfield


    【解决方案1】:

    默认情况下,使用TextEditingController 而不设置selection 属性,将位于第一个字符/文本值。 你可以试试这样的:

    String textValue = 'Existing Text Here';

    TextField(
      controller: TextEditingController()..value = TextEditingValue(
      text: textValue,
      selection: TextSelection.fromPosition(
      TextPosition(offset: textValue.length))
        )
      ),
    

    【讨论】:

    • 我以前试过这个,但这不是我想要的。我想要的是在用户点击的地方显示光标,就像你第一次点击 TextField 一样。有没有办法重置 TextEditingController 让它就像你第一次编辑它一样?
    猜你喜欢
    • 2022-06-27
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多