【问题标题】:Is there a way to get only the text changed when text is changed in a textfield in flutter?有没有办法在颤动的文本字段中更改文本时仅更改文本?
【发布时间】:2020-09-03 11:17:27
【问题描述】:

我有一个颤动的文本字段,我想知道是否有办法只获取更改的文本,我们可以将其称为 delta,当文本字段中的文本发生更改时。

TextField(
    style: TextStyle(color: Colors.red),
    controller: _controller,
    focusNode: _focusNode,
    cursorColor: Colors.red,
    onChanged: (s) {
      print(s);
    },
),

使用以下代码,我只会在文本更改时获取整个文本值。

例如:如果文本字段中的文本是“Hello worl”并且我添加了一个“d”,那么 onChanged 中的值就是“Hello world”。 有没有办法只获取插入/删除/剪切/粘贴的文本以及执行操作的位置?

我想获取一个自定义类型的变量,比如说 CustomTextAction,它包含一个索引,用于更改文本的位置、操作类型、执行的操作类型以及更改的值或其他内容相似的。例如,在上面的情况下,它将是:

CustomTextAction:
- index: 10
- type: "insertion"
- value: "d"

这样的功能是否已经存在于 Flutter 中,还是我应该自己编写代码?

【问题讨论】:

    标签: android flutter dart


    【解决方案1】:

    这就是逻辑。

    class _MyWidgetState extends State<MyWidget> {
      getNewValue(String oldValue, String currentValue) {
        if (oldValue.length < currentValue.length) {
          String newLetter = currentValue.replaceAll(oldValue, "")[0];
          print("You added: " + newLetter);
          return newLetter;
        } else {
          String newLetter = oldValue.replaceAll(currentValue, "")[0];
          print("You deleted: " + newLetter);
          return newLetter;
        }
      }
    
      String oldValue = "";
    //   TextEditingController _controller = new TextEditingController();
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Column(
            children: [
              TextFormField(onChanged: (currentValue) {
                String newValue = getNewValue(oldValue, currentValue);
                oldValue = currentValue;
                print(newValue);
              }),
            ],
          ),
        );
      }
    }
    

    它只给出了您添加的最后一个字母,但您可以使用 onEditingComplete 中的函数来获得完整的更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-17
      • 2016-04-19
      • 2018-12-10
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      相关资源
      最近更新 更多