android - 在无状态小部件中使用 TextFormField 在 flutter 中非常困难

标签 android ios flutter flutter-layout

我正在尝试在无状态小部件中使用 TextFormField 以及 ScopedModel 来处理其中的文本并面临以下各种问题。

  1. 我尝试使用 Controller 作为字段,但每次我输入一些文本并在键盘上按完成时,文本都会被清除。不知道为什么。

  2. 如果我删除 Controller ,文本会保留在字段中,但会产生关于如何从字段中获取文本的新问题。我通过使用回调 onFieldSubmitted 解决了它。

  3. 但事实证明,onFieldSubmitted 只有在我们点击键盘上的完成按钮时才会被调用。如果我在字段中输入文本而不是单击确定,而是单击另一个字段,则不会调用回调,并且我将无法跟踪用户在字段中输入的内容。

有什么解决办法吗?

附上问题示例代码。

  class LoginPageStateless extends StatelessWidget {

  final loginUsernameController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: true,
      body: ScopedModelDescendant<AccountModel>(
        builder: (context, child, model) {
          return Form(
            //key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                TextFormField(
                  style: TextStyle(fontSize: 15.0),
                  decoration: InputDecoration(
                    labelText: 'Email id',
                    hintText: 'johndoe@ipropal.com',
                  ),
                  controller: loginUsernameController,
                  onFieldSubmitted: model.updateLoginUsernameText,
                ),
                TextFormField(
                  style: TextStyle(fontSize: 15.0),
                  decoration: InputDecoration(
                    labelText: 'Password',
                  ),
                  controller: loginUsernameController,
                  onFieldSubmitted: model.updateLoginUsernameText,
                  obscureText: true,
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

最佳答案

您不能也不应该使用 Stateless 小部件来存储长期变量。

问题是,这正是你想要的。 TextEditingController 是一个应该在渲染之间保留的类实例。但是通过将其存储到 StatelessWidget 中,您基本上可以在每次更新后重新创建它。

您应该将您的小部件转换为 Stateful。并将该 Controller 移动到 State 部分

关于android - 在无状态小部件中使用 TextFormField 在 flutter 中非常困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980118/

相关文章:

android - Android中如何模仿finishAffinity?

java - 将变量传递给类

android - 更新查询的返回值为0

ios - 弱 self 在 block 内变为零,但我想在 block 内使用 self 对象

android - 将 XML 字符串编码为 EXI 并通过 websocket 发送

ios - 点击下一步/完成时在不同 UITableViewCell 中的 UITextField 中导航

ios - 在同一个项目中使用不同的 pod 版本

dart - 如何在没有 Scaffold.drawer 的情况下使用 Drawer?

flutter - 选项卡栏中的抽屉也显示在条子应用程序栏中

flutter - 如何将文本与 RadioListTile 对齐