繁体   English   中英

具有默认文本的TextFormField

[英]TextFormField with default text

我想拥有一些FormTextFields,其中包含一些用户可以更改的默认文本。 我的问题是,修改了字段后,如果按一下另一个字段或按钮,一切都很好,但是,如果按键盘上的“完成”按钮,则会返回默认文本,删除用户插入的新内容。 到目前为止,这是我所做的:

class _LoginSettingsViewState extends State<LoginSettingsView> {

  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

  var _userTextController = new TextEditingController();

@override
  Widget build(BuildContext context) {

    _userTextController.text = "test";

 return Scaffold(

      appBar: AppBar(
        title: Text("Settings"),
      ),

      body: ListView(
        children: <Widget>[
          new Container(
            margin: EdgeInsets.only(
              left: 10.0,
              right: 10.0,
              top: MediaQuery.of(context).size.height / 10
            ),
            child: Form(
                key: _formKey,
                child: Column(
                  children: <Widget>[
                    TextFormField(
                      decoration: _fieldDecoration("user", null),
                      controller: _userTextController,
                      validator: (val) => val.isEmpty ? "Insert user" : null,
                      onSaved: (val){
                        print(val);
                      },
                    ),

您是在build方法中设置默认文本,每次重新构建UI时,都会调用build方法,因此您可以放回默认文本。

将您的初始化initState方法中

@override
void initState() {
  super.initState();
  _userTextController.text = "test";
}

也不要忘记布置控制器

@override
void dispose() {
  _userTextController.dispose();
  super.dispose();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM