首页 > 解决方案 > 在 Flutter 中获取 TextFormField 的选择

问题描述

我的目标是获取 TextFormField 的选定文本,但是每次按下按钮时,TextFormField 都会失去焦点,并且控制台中的打印仅显示 -1 和 -1 之间的选择。

几周前它确实有效,最新版本中的行为是否发生了变化?我在稳定的 Flutter 频道上。( Flutter Channel stable, 2.5.0)

这是我的测试示例:

import 'package:flutter/material.dart';

class Play extends StatefulWidget {
  const Play({Key? key}) : super(key: key);

  @override
  _PlayState createState() => _PlayState();
}

class _PlayState extends State<Play> {
  TextEditingController _controller = TextEditingController();
  FocusNode _node = FocusNode();

  void _onPressed() {
    TextSelection selection = _controller.selection;

    print("selection.start: ${selection.start}");
    print("selection.end: ${selection.end}");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextFormField(
            focusNode: _node,
            controller: _controller,
          ),
          ElevatedButton(
            onPressed: _onPressed,
            child: Text("do something"),
          ),
        ],
      ),
    );
  }
}

标签: flutter

解决方案


由于它在移动设备上运行良好,我会说这是 Flutter 中的一个错误,但不要害怕!欢迎来到变通办法和临时解决方案TM的世界;用这个替换你的整个_onPressed方法:

  int start = -1;
  int end = -1;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() async {
      TextSelection selection = _controller.selection;
      if (selection.start > -1) start = selection.start;
      if (selection.end > -1) end = selection.end;
    });
  }

  void _onPressed() {
    print(start);
    print(end);
  }

如果有什么不是很清楚,请告诉我,我很乐意通过进一步的解释来编辑答案。

DartPad 示例

Flutter 社区希望您提交错误报告(如果它尚不存在)!:D


推荐阅读