问题描述
我正在使用提供程序进行状态管理.我处于表单中存在多种类型的字段的情况.问题在于文本字段每当我更改文本"时,它的行为都会怪异地像输入的文本以相反的顺序显示.
I am using provider for state management. I am in a situation where there are multiple types of fields in my form. The problem is with text-fieldWhenever I change Text it is behaving weirdly like the text entered is displayed in reverse order.
class MyProvider with ChangeNotifier{
String _name;
String get name => _name;
setname(String name) {
_name = name;
notifyListeners();
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final MyProvider myProvider = Provider.of<MyProvider>(context);
final TextEditingController _nameController = TextEditingController(
text: myProvider.name,
);
return TextField(
controller: _nameController,
onChanged: myProvider.setname,
);
}
推荐答案
之所以会发生这种情况,是因为在每个小部件构建上都会创建 TextEditingController
的新实例,以及有关当前光标位置的信息( TextEditingValue
)迷路了.
It happens because new instance of TextEditingController
is created on every widget build, and information about current cursor position (TextEditingValue
) is getting lost.
在 initState
方法中一次创建一个控制器,然后在 dispose
方法中对其进行处理.
Create a controller once in initState
method and dispose of it in dispose
method.
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
TextEditingController _nameController;
@override
void initState() {
final MyProvider myProvider = Provider.of<MyProvider>(context, listen: false);
super.initState();
_nameController = TextEditingController(text: myProvider.name);
}
@override
void dispose() {
_nameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final MyProvider myProvider = Provider.of<MyProvider>(context);
return TextField(
controller: _nameController,
onChanged: myProvider.setname,
);
}
}
这篇关于如何在Flutter中通过提供者使用textEditiing控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!