无法从有状态小部件访问属性

时间:2021-01-10 06:21:48

标签: flutter dart

class PasswordTextField extends StatefulWidget {
  final String hintText;
  final IconData icon;
  final TextEditingController controller;
  final FormFieldValidator<String> validator;
  PasswordTextField({
    Key key,
    this.hintText ,
    this.icon = Icons.lock,
    this.validator,
    this.controller
  }) : super(key: key);
  @override
    _PasswordTextFieldState createState() => _PasswordTextFieldState();
  }
  class _PasswordTextFieldState extends State<PasswordTextField> {

    var _passwordVisible;
    var _iconColor;
    @override
    void initState() {
      _passwordVisible = true;
      _iconColor = Colors.grey;
    }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return TextFieldContainer(
      child: TextFormField(
        controller: controller, //here
        validator: validator, //here
        obscureText: _passwordVisible,
        cursorColor: kPrimaryightColor,
        decoration: InputDecoration(
          labelText: "Your Password",
          labelStyle: TextStyle(color: kPrimaryColor) ,
          hintText: hintText, /ere
          border: InputBorder.none,
          icon: Icon(
            icon, //here
            color: kPrimaryColor,
          ),
          suffixIcon: IconButton(
            icon: Icon(Icons.remove_red_eye),
          color: _iconColor,
          onPressed: (){
            setState(() {
              if(_passwordVisible == true){
                _passwordVisible = false;
                _iconColor = kPrimaryColor;
              }else{
                _passwordVisible = true;
                _iconColor = Colors.grey;
              }
            });
          },
        ),
      ),
    ),
    );
  }
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    throw UnimplementedError();
  }
}

我想从我的有状态小部件访问一些属性,但我不知道它是如何在无状态下工作的,还有其他方法可以在另一个文件上使用它吗?

我是这样用的 密码文本字段( 验证器:(值){ 如果(值。isEmpty){ return "请插入内容";
}else if(value.length < 6){ 返回“输入正确的密码格式(6 个字符)”; }别的{ 返回空; }

1 个答案:

答案 0 :(得分:0)

您可以使用预定义的字段 state(即 widget)访问 widget.controller 类中的 Stateful 小部件类中声明的字段。所以你的代码看起来像这样:

  @override
  Widget build(BuildContext context) {
    return TextFieldContainer(
      child: TextFormField(
        controller: widget.controller, // here
        validator: widget.validator, // here
        obscureText: _passwordVisible,
        cursorColor: kPrimaryightColor,
        decoration: InputDecoration(
          labelText: "Your Password",
          labelStyle: TextStyle(color: kPrimaryColor) ,
          hintText: widget.hintText, // here
          border: InputBorder.none,
          icon: Icon(
            widget.icon, // here
            color: kPrimaryColor,
          ),
          // Define other controls
        ),
      ),
    );
  }