在 flutter 中将所有文本字段格式化为相同格式

format all textfields the same in flutter

我正在努力学习 Flutter。我有下面我想要的 TextField 设置,我可以复制并粘贴应用程序中每个 TextField 的所有 settings/properties,但是是否有更好的方法使所有 TextField 具有相同的 setting/properties?

    Flexible(
        child: Padding(
          padding: EdgeInsets.all(20.0),
          child: TextField(
            maxLength: 5,
            maxLengthEnforcement: MaxLengthEnforcement.enforced,
            keyboardType: TextInputType.numberWithOptions(decimal: true, signed: false, ),
            inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp(r"[0-9.]"))],
            //keyboardType: TextInputType.number,
            decoration: InputDecoration(
              labelStyle: TextStyle(color: Colors.black,
              fontStyle: FontStyle.normal, fontSize: 20, fontWeight: FontWeight.bold ),
              floatingLabelAlignment: FloatingLabelAlignment.center,
              //border: OutlineInputBorder(),
              border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(45),
              ),
              floatingLabelBehavior: FloatingLabelBehavior.always,
              labelText: 'Empty Weight',
              filled: true,
              fillColor: Colors.grey[350],
            ),
          ),
        ),
      ),

当然,基本上,这就是 Flutter 背后的主要思想——您正在构建可重用的组件(小部件),然后使用它们来构建您的应用程序。

  1. 确定 TextField 的哪些属性应该更改。例如。让我们考虑(根据您的示例)可能是 labelTextmaxLength.

  2. 创建一个包装 TextField 的自定义 Widget,并将提取的属性定义为 Widget 属性,并将它们用作 TextField:

    的变量
class CustomTextField extends StatelessWidget {
  final String labelText;
  final int maxLength;

  const CustomTextField({
    required this.labelText,
    required this.maxLength,
  });

  @override
  Widget build(BuildContext context) {
    return TextField(
      maxLength: maxLength,
      maxLengthEnforcement: MaxLengthEnforcement.enforced,
      keyboardType: TextInputType.numberWithOptions(
        decimal: true,
        signed: false,
      ),
      inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r"[0-9.]"))],
      //keyboardType: TextInputType.number,
      decoration: InputDecoration(
        labelStyle: TextStyle(
            color: Colors.black,
            fontStyle: FontStyle.normal,
            fontSize: 20,
            fontWeight: FontWeight.bold),
        floatingLabelAlignment: FloatingLabelAlignment.center,
        //border: OutlineInputBorder(),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(45),
        ),
        floatingLabelBehavior: FloatingLabelBehavior.always,
        labelText: labelText,
        filled: true,
        fillColor: Colors.grey[350],
      ),
    );
  }
}
  1. 在代码中使用您的CustomTextField
Flexible(
  child: Padding(
    padding: EdgeInsets.all(20.0),
    child: CustomTextField(
      maxLength: 5,
      labelText: 'Empty Weight',
    ),
  ),
);