我正在努力學習 Flutter。我有以下 TextField 設定,我可以復制并粘貼應用程式中每個 TextField 的所有設定/屬性,但是有沒有更好的方法讓所有 TextField 具有相同的設定/屬性?
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],
),
),
),
),
uj5u.com熱心網友回復:
當然,基本上,這是 Flutter 背后的主要思想——你正在構建可重用的組件(小部件),然后使用它們來構建你的應用程式。
確定
TextField應該更改的屬性。例如,讓我們考慮(從您的示例中)可能是labelTextandmaxLength。創建一個自定義 Widget 包裝
TextField并將提取的屬性定義為 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],
),
);
}
}
CustomTextField在代碼中使用您的:
Flexible(
child: Padding(
padding: EdgeInsets.all(20.0),
child: CustomTextField(
maxLength: 5,
labelText: 'Empty Weight',
),
),
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/439358.html
