我想为文本字段提供一个初始值,并重新绘制一个空值以清除文本。用Flutter的api实现这一点的最佳方法是什么?
当前回答
你可以使用TextFormField代替TextField,并使用initialValue属性。例如
TextFormField(initialValue: "I am smart")
其他回答
如果您使用文本表单字段并将数据从上一页传递到下一页文本表单字段,请使用此选项
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);
}
我在这里见过很多方法。然而,我认为这比其他答案更有效或至少更简洁。
TextField(
controller: TextEditingController(text: "Initial Text here"),
)
TextEdittingController _controller = new TextEdittingController(text: "your Text");
or
@override
void initState() {
super.initState();
_Controller.text = "Your Text";
}
你可以做以上所有的事情,但如果你想让API在加载时显示你的数据,它会像配置文件页面一样显示。下面是代码:
TextEditingController _nameController = TextEditingController(); // initialize the controller
// when API gets the data, do this:
_nameController.text = response.data.fullName; or _nameController.text = "Apoorv Pandey"
我希望这能澄清一切。编码快乐!
当你使用TextEditingController
如果使用TextEditingController,请将其文本字段设置为所需的值
TextEditingController txtController = TextEditingController()..text = 'Your initial text value';
TextField( controller: txtController ..... )
当你不使用TextEditingController
如果你没有使用texteditingcontroller,直接从TextField小部件使用initialValue字段:
TextFormField( initialValue: "Your initial text value" )