[英]Flutter - How to change TextFormField fillColor according Validation result
I want to change TextFormField
fillColor
according to result of validation.我想根据验证结果更改
TextFormField
fillColor
。 Same as below:与以下相同:
use a global bool variable that is changed depending on validation result使用根据验证结果更改的全局布尔变量
bool correct = null
.
.
.
TextFormField(
fillColor: correct ? Colors.green : correct! ? Colors.red : Colors.white //extra check for null if no value yet
validate:(value) {
if (value){
correct = true
}
else {
correct = false
}
}
)
you can use this code directly您可以直接使用此代码
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
const TestPage({Key? key}) : super(key: key);
@override
State<TestPage> createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
final formKey = GlobalKey<FormState>();
String text = '';
bool validate = false;
Color green = Colors.green.shade50;
Color red = Colors.red.shade50;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) {
validate = false;
if (value.toString().isEmpty ||
!value.toString().contains('@')) {
return 'Enter valid Email';
} else {
validate = true;
}
},
decoration: InputDecoration(
hintText: 'Email',
filled: true,
fillColor: validate ? green : red,
prefixIcon: Icon(
Icons.alternate_email_outlined,
color: validate ? Colors.green : Colors.red,
),
suffixIcon: validate
? const Icon(
Icons.check_outlined,
color: Colors.green,
)
: const Icon(
Icons.close_outlined,
color: Colors.red,
),
errorBorder: borderStyleFalse,
enabledBorder: validate ? borderStyleTrue : borderStyleFalse,
focusedBorder: validate ? borderStyleTrue : borderStyleFalse,
focusedErrorBorder: borderStyleFalse,
),
onChanged: (value) {
setState(() {
text = value;
});
},
),
ElevatedButton(
onPressed: () {
formKey.currentState!.validate();
},
child: const Text('call'),
),
],
),
),
),
);
}
OutlineInputBorder borderStyleTrue = OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: Colors.green),
);
OutlineInputBorder borderStyleFalse = OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: Colors.red),
);
}
and this the result这就是结果
when you open the screen enter image description here当您打开屏幕时,请在此处输入图像描述
when you write and wrong message enter image description here当您写错信息时,请在此处输入图像描述
when you write email right enter image description here当您写电子邮件时,请在此处输入图像描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.