Issue
I’m trying to learn Flutter. I have the below TextField setup as I would like it, I could copy and paste all the settings/properties for each TextField in the app, however is there a better way to make all of the TextFields have the same 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],
),
),
),
),
Solution
Of course and basically, this is the main idea behind Flutter – you are building reusable components (widgets) and later use them to build your app.
-
Identify what properties of your
TextField
should change. E.g. let’s consider (from your example) that could belabelText
andmaxLength
. -
Create a custom Widget that wraps the
TextField
and defines the extracted properties as Widget properties and use them as variables for theTextField
:
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],
),
);
}
}
- User your
CustomTextField
in the code:
Flexible(
child: Padding(
padding: EdgeInsets.all(20.0),
child: CustomTextField(
maxLength: 5,
labelText: 'Empty Weight',
),
),
);
Answered By – mkobuolys
Answer Checked By – Candace Johnson (FlutterFixes Volunteer)