为什么每当触发 onChanged 事件时,TextField 中的光标就会跳到文本开头?

问题描述 投票:0回答:1

我的应用程序有(除其他外)一个

TextField
ElevatedButton
。我正在使用
Provider
管理状态。我希望当 TextField 的内容更改时按钮颜色从白色变为蓝色。

我在文本字段中有此代码:

 onChanged: (_) {
   context.read<Data>().changeButtonColor();
   },

这个在 ElevatedButton 中:

style: ElevatedButton.styleFrom(
   backgroundColor: context.watch<Data>().buttonColor),

这在提供者中:

Color buttonColor = Colors.white;
void changeButtonColor() {
  buttonColor = Colors.blue;
  notifyListeners();
}

按钮的颜色按预期变化。然而,我遇到的问题是,一旦触发

TextField
事件,
onChanged
中的光标就会跳转到文本的开头。这使得该应用程序无法使用。

为什么光标会这样?如何使代码按预期工作,i.e.,而不使

TextField
光标跳到文本开头?


作为参考,这是两个小部件的完整代码:

// Note Text TextField---------------------------------
              Padding(
                padding: EdgeInsets.only(
                  top: 15,
                  bottom: 15,
                ),
                child: TextField(
                  controller: noteTextController,
                  keyboardType: TextInputType.multiline,
                  maxLines: null,
                  minLines: 10,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    fillColor: Colors.white,
                  ),
                  onChanged: (_) {
                    context.read<Data>().changeButtonColor();
                  },
                ),
              ),

 // Save Button------------------------------------------
              Padding(
                padding: EdgeInsets.only(
                  top: 15,
                  bottom: 15,
                ),
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      backgroundColor: context.watch<Data>().buttonColor),
                  onPressed: () async {
                    selNote = context.read<Data>().selectedNote;

                    var title = noteTitleController.text;
                    var content = noteTextController.text;
                    // If this is a new note ... create it
                    if (selNote == null) {
                      context.read<Data>().add(title, content);
                    } else {
                      // If this is an already existing note ... update it
                      selNote!.title = title;
                      selNote!.content = content;
                      context.read<Data>().update(title: title, content: content);
                    }
                  },
                  child: Text('Save'),
                ),
              ),
flutter textfield onchange flutter-provider
1个回答
0
投票

尝试修改 TextField 的控制器文本的值,当更改时被调用:

onChanged(newValue){

  // mange container's state then

  noteTextController.text = newValue;

}

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.