从扩展 StatefulWidget 的 class 调用 setState

Call setState from class that extends StatefulWidget

如果我使用 class 对象更新变量,应该会调用构建方法,但我无法从 StatefulWidget class.

调用 setState
class CustomErrorFormField extends StatefulWidget {

  @override
  _CustomErrorFormFieldState createState() {
    return _CustomErrorFormFieldState();
  }

  List<String> errorList = []; //this variable will get updated using below function
    
  void setErrorList(List<String> listOfError) {
        errorList = listOfError;
   }

}
class _CustomErrorFormFieldState extends State<CustomErrorFormField> {


  @override
  void initState() {
    super.initState();
  }


 @override
 Widget build(BuildContext context) {

    print(widget.errorList); //this is not printing updated value

    return .....
  }
}

现在在其他一些 class 我将更新 errorList 变量

 nameTextFild = CustomErrorFormField(
       key: ValueKey(count),
      labelName: "Name",
      iContext: context,
      onChanged: (String value) {


        setState(() {
          count++;
          if (!value.contains(RegExp(r'[0-9]'))) {
            nameTextFild!.setErrorList([]); //updating but changes not appearing (setState of this widget is not getting called)
          } else {
            nameTextFild!.setErrorList(["Invalid characters, use letters only."]);
          }

        });



      },
    );

建议您从小部件外部更改小部件的状态。

您应该做的是将验证逻辑作为 function 传递并让小部件处理状态更改。

自定义表单字段:

import 'package:flutter/material.dart';

class CustomErrorFormField extends StatefulWidget {
  //Take the validation logic as a parameter.
  final List<String> Function(String value) validator;
  const CustomErrorFormField({required this.validator});

  @override
  _CustomErrorFormFieldState createState() {
    return _CustomErrorFormFieldState();
  }
}

class _CustomErrorFormFieldState extends State<CustomErrorFormField> {
  
  //Keep the state inside the widget itself
  List<String> errorList = [];

  //Update the state from inside the widget
  void setErrorList(List<String> listOfError) {
    setState(() {
      errorList = listOfError;
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      child: TextFormField(
        validator: (String value){
           //Use the validation logic to decide the error.
           setErrorList(widget.validator(value))
          }
        }
      ),
    );
  }
}

我以 TextFormField 为例,您可以使用任何在更改时接受 callback 的小部件。

如果您要从头开始制作所有内容,您可以将 validator 函数附加到文本更改时触发的 callback。通常这是在 controller.

的帮助下完成的

用法:

final nameTextFild = CustomErrorFormField(
  key: ValueKey(count),
  labelName: "Name",
  iContext: context,
  validator: (String value) {
    if (!value.contains(RegExp(r'[0-9]'))) {
      return [];
    } else {
      return ["Invalid characters, use letters only."];
    }
  },
);