我想为文本字段提供一个初始值,并重新绘制一个空值以清除文本。用Flutter的api实现这一点的最佳方法是什么?
当前回答
你不需要在小部件范围内定义一个单独的变量,只需内联即可:
TextField(
controller: TextEditingController()..text = 'Your initial value',
onChanged: (text) => {},
)
其他回答
TextEdittingController _controller = new TextEdittingController(text: "your Text");
or
@override
void initState() {
super.initState();
_Controller.text = "Your Text";
}
至于上述答案都是正确的,但有一件事是缺失的,我想添加到它是如何自定义TextFormField的默认文本的风格。
TextEditingController textController = TextEditingController(text: '4');
TextFormField(
controller: textController,
// This style property will customize the default controller text
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
对于这种情况,我更喜欢使用TextEditingController而不是initialValue,因为如果你想改变它以后或修改它,那么textController将不断监听你的TextFormField输入的变化。 这是我个人的观点,如果我错了请告诉我。
如果您使用文本表单字段并将数据从上一页传递到下一页文本表单字段,请使用此选项
class ProfilePage extends StatefulWidget {
late final String fname;
ProfilePage({required this.fname});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
final _form = GlobalKey<FormState>();
late var FullNameController = TextEditingController(text: widget.fname);
}
(来自邮件列表。这个答案不是我想出来的。)
class _FooState extends State<Foo> {
TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = new TextEditingController(text: 'Initial value');
}
@override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new TextField(
// The TextField is first built, the controller has some initial text,
// which the TextField shows. As the user edits, the text property of
// the controller is updated.
controller: _controller,
),
new RaisedButton(
onPressed: () {
// You can also use the controller to manipuate what is shown in the
// text field. For example, the clear() method removes all the text
// from the text field.
_controller.clear();
},
child: new Text('CLEAR'),
),
],
);
}
}
由于没有一个答案提到它,TextEditingController应该在使用后被丢弃。如:
class MyWidget extends StatefulWidget {
const MyWidget({Key? key}) : super(key: key);
@override
MyWidgetState createState() => MyWidgetState();
}
class MyWidgetState extends State<MyWidget> {
final myController = TextEditingController(text: "Initial value");
@override
Widget build(BuildContext context) {
return TextField(
controller: myController,
);
}
@override
void dispose() {
// dispose it here
myController.dispose();
super.dispose();
}
}
推荐文章
- 错误地使用父数据小部件。扩展小部件必须放置在flex小部件中
- 颤振给容器圆形边界
- Flutter: RenderBox没有布局
- 颤振插件未安装错误;当运行'扑动医生'时
- 如何改变appBar返回按钮的颜色
- 如何在扑动中设置按钮的宽度和高度?
- 我如何“休眠”Dart程序
- 在Flutter app上检查是否有网络连接
- 如何禁用或覆盖Android的“返回”按钮,在扑动?
- 如何在扑动中垂直和水平居中文本?
- Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10:, null)
- 如何在扑动中格式化日期时间
- 在Flutter中Column的子元素之间的空间
- Visual Studio代码- URI的目标不存在" package:flutter/material.dart "
- Flutter:升级游戏商店的版本代码