在Flutter中为Formfield和控制器构建包装器小部件 [英] building a wrapper widget for a formfield and controller in flutter

查看:43
本文介绍了在Flutter中为Formfield和控制器构建包装器小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为包含控制器的TextFormField创建包装器小部件,因为我必须在验证函数内部访问TextFormField的值.使用下面粘贴的代码,每次MyTextField获得焦点时,都会再次调用contructorbuild方法.这会导致myInputController重新创建,这会导致我每次单击该文本字段时都为空.

I like to create a wrapper widget for a TextFormField which includes the controller because I have to access the value of the TextFormField inside the validation function. With the code pasted below, every time the MyTextField gets the focus the contructor and the build method were called again. This causes a recreationg of myInputController which causes that the textfield is empty every time I click on it.

class MyTextField extends StatelessWidget {

  TextEditingController myInputController;

  MyTextField() {
       myInputController = TextEditingController();
  } 

  @override
  Widget build(BuildContext context) {
    print("build called");
    return TextFormField(
      controller: myInputController,
    );
  }
}

在应用程序内部,我像这样插入了小部件:

Inside the app I inserted the widget like this:

 ...
 child: SingleChildScrollView(
   child: Form(
     key: _formKey,
     child: Column(
       children: <Widget>[
       MyTextField(),
       TextFormField(
              ),
       ...

推荐答案

如果需要使用Form() widget,则应使用StatefulWidget而不是StatelessWidget

If you need to use Form()widget then you should use StatefulWidget instead of StatelessWidget

因此,您只想在代码中使用StatefulWidget

So, you just want to use StatefulWidget in you code

这篇关于在Flutter中为Formfield和控制器构建包装器小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆