请帮我问两个问题。
第一个问题。为什么文本值消失?[修正]由@praneeth
我添加了GIF
please click
我用这种方式编写代码,
在我的小部件中,我调用了UsernameTextField类。
小部件看起来像这样,
widget build>willPopScope>scaffold>form>listView>children>
容器(在容器下面)我还添加了key: _scaffoldKey,key: formKey,

 Container(
                padding: EdgeInsets.all(16.0),
                margin: EdgeInsets.only(top: 30.0),
                child: UsernameTextField(),
              ),

用户名文本字段()
class UsernameTextField extends StatefulWidget{
  final usernameController = TextEditingController();
  @override
  State<StatefulWidget> createState() {
    return UsernameTextFieldState(usernameController);
  }
}

class UsernameTextFieldState extends State<UsernameTextField>{
  final usernameController;
  UsernameTextFieldState(this.usernameController);

  @override
  Widget build(BuildContext context) {
    return AppTextField(
        decoration: InputDecoration(
          contentPadding: const EdgeInsets.all(20.0),
          labelText: AppTranslations.of(context)
              .text("loginpage_username"),
        ),
        myController: usernameController,
        textInputType: TextInputType.emailAddress
    );
  }
}

apptextfield()类,我将这个类用于我的每个textfield小部件
class AppTextField extends StatelessWidget {
  final InputDecoration decoration;
  final myController;
  final TextInputType textInputType;
  AppTextField({
    this.decoration,
    this.myController,
    this.textInputType
  });

  @override
  Widget build(BuildContext context) {
    return TextFormField(
        controller: myController,
        keyboardType: textInputType,
        textAlign: TextAlign.left,
        decoration: decoration
    );}}

第二个问题。如何获取textfield值?
在我调用的buttononPressed()方法中,我调用了validation方法,但结果是null
usernameValidation(){
  String username = UsernameTextField().usernameController.text;
  print(username);
}

最佳答案

首先,通过扩展为statefulwidget而不是statelesswidget,将usernametextfield类转换为有状态的类。
然后您可以从usernameController.text
更新

    class UsernameTextField extends StatefulWidget{
      final usernameController = TextEditingController();
      UsernameTextField(this.usernameController)

      @override
      State<StatefulWidget> createState() {
        return UsernameTextFieldState(usernameController);
      }
    }

    class UsernameTextFieldState extends State<UsernameTextField>{

      @override
      Widget build(BuildContext context) {
        return AppTextField(
            decoration: InputDecoration(
              contentPadding: const EdgeInsets.all(20.0),
              labelText: AppTranslations.of(context)
                  .text("loginpage_username"),
            ),
            myController: widget.usernameController,
            textInputType: TextInputType.emailAddress
        );
      }
    }

关于flutter - TextFormField值消失了,如何获取textFormField值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56471639/

10-11 01:15