Flutter Text Validation in CupertinoTextField
4,102
You need to use TextEditingController
& perform the validation manually.
Basic validation for checking if the field is empty or not.
code:
TextEditingController _myPhoneField = TextEditingController();
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
if (_myPhoneField.text.isEmpty) {
showCupertinoDialog(
context: context,
builder: (context) {
return CupertinoAlertDialog(
title: Text('error'),
content: Text('Phone Field is Empty'),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('ok'))
],
);
});
} else {
// Validation passed
}
},
child: Text('submit'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CupertinoTextField(
clearButtonMode: OverlayVisibilityMode.editing,
controller: _myPhoneField, // Add this
prefix: Padding(
padding: EdgeInsets.all(8.0),
child: Icon(
CupertinoIcons.phone_solid,
),
),
style: TextStyle(
fontSize: 30,
),
keyboardType: TextInputType.number,
maxLength: 10,
maxLines: 1,
maxLengthEnforced: true,
placeholder: 'Enter Phone',
onChanged: (v) {
print(v);
},
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: CupertinoColors.inactiveGray,
),
borderRadius: BorderRadius.circular(32.0),
),
),
],
),
);
}
Author by
Gabriele Cinà
Self starter and passionate second year Computer Science student with experience in programming and mathematics outside university courses. Ability to learn other coding languages and frameworks as need. Aspiring to apply my knowledge, gained from both the coursework and personal projects, to real-world challenges by completing challenging technical projects.
Updated on December 13, 2022Comments
-
Gabriele Cinà over 1 year
I want to add some text validation to my CupertinoTextField but there's no validator for this Widget. How can I solve this?
I tried searching on the internet for some solutions but nothing came out.
CupertinoTextField( prefix: Padding( padding: EdgeInsets.all(8.0), child: Icon( customIcon, ), ), style: TextStyle( fontSize: 30, ), keyboardType: TextInputType.number, maxLength: maxLength, maxLines: 1, maxLengthEnforced: true, placeholder: placeholderText, onChanged: onChangedFunction, decoration: BoxDecoration( border: Border.all( width: 2.0, color: CupertinoColors.inactiveGray, ), borderRadius: BorderRadius.circular(32.0), ), )