带有默认文本的TextFormField

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

我希望有一些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);
                      },
                    ),
dart flutter
1个回答
3
投票

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

移动你在initState方法内初始化

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

也不要忘记丢弃你的控制器

@override
void dispose() {
  _userTextController.dispose();
  super.dispose();
}
© www.soinside.com 2019 - 2024. All rights reserved.