[英]how to display validation error message out from the textfield in flutter
如何從框中顯示“此字段為必填項”消息。 此消息將在按鈕單擊時顯示。
這是文本字段代碼
-------------------編輯的問題-------------------
這是您的代碼,並通過添加一個 textformfield 對其進行了修改
import 'package:flutter/material.dart';
class ExperimentApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
),
home: ExperimentHome(),
);
}
}
class ExperimentHome extends StatelessWidget {
final GlobalKey<FormFieldState> formFieldKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: RoundedInputField(
formFieldKey: formFieldKey,
icon: Icons.edit,
labelText: 'Label',
validate: (value) {
if (value == null || value.isEmpty) {
return "This field is required";
}
return null;
},
),
),
),
//this is one more TextFormField
RoundedInputField(
formFieldKey: formFieldKey,
icon: Icons.edit,
labelText: 'Label1',
validate: (value) {
if (value == null || value.isEmpty) {
return "This field is required";
}
return null;
},
),
IconButton(
icon: Icon(Icons.check),
onPressed: () {
// you need to call `.validate` to actually validate the field.
formFieldKey.currentState.validate();
},
)
],
),
),
);
}
}
class RoundedInputField extends StatelessWidget {
final IconData icon;
final FormFieldValidator<String> validate;
final String labelText;
final GlobalKey<FormFieldState> formFieldKey;
// (before flutter 2.0) drop `required`
const RoundedInputField({
Key key,
@required this.formFieldKey,
@required this.labelText,
@required this.icon,
@required this.validate,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextFormField(
key: formFieldKey,
validator: validate,
decoration: InputDecoration(
icon: Icon(
icon,
color: Colors.blue,
),
labelText: labelText,
),
);
}
}
這是錯誤
════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderTransform#3842d NEEDS-LAYOUT NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1940 pos 12: 'hasSize'
The relevant error-causing widget was
TextFormField-[LabeledGlobalKey<FormFieldState<dynamic>>#a4b32]
lib\abc.dart:87
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
Multiple widgets used the same GlobalKey.
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
Multiple widgets used the same GlobalKey.
════════════════════════════════════════════════════════════════════════════════
它顯示純白屏幕為 output
這對你有用。
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.anyColor,
width: 2),
),
focusedErrorBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.anyColor,
width: 2),
),
errorBorder:
(value.isEmpty)
? UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.anyColor),
)
: InputBorder.none,
errorText:
(value.isEmpty)
? "Minimum 3 characters required"
: null,
errorStyle: anyTextStyle(),
hintText: "Name",
hintStyle:
anyTextStyle()),
您需要使用GlobalKey<FormFieldState>
並在該字段上實際調用.validate
來驗證該字段。
當您調用.validate
時, TextFormField
將驗證該字段並在 validate 方法返回String
時顯示錯誤消息。
有關TextFormField
的更多信息: https://api.flutter.dev/flutter/material/TextFormField-class.html
代碼示例(存在一些語法差異,因為您似乎使用的是舊版本的 dart):
import 'package:flutter/material.dart';
void main() async {
runApp(ExperimentApp());
}
class ExperimentApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
),
home: ExperimentHome(),
);
}
}
class ExperimentHome extends StatelessWidget {
final GlobalKey<FormFieldState> formFieldKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: RoundedInputField(
formFieldKey: formFieldKey,
icon: Icons.edit,
labelText: 'Label',
validate: (value) {
if (value == null || value.isEmpty) {
return "This field is required";
}
return null;
},
),
),
),
IconButton(
icon: Icon(Icons.check),
onPressed: () {
// you need to call `.validate` to actually validate the field.
formFieldKey.currentState!.validate();
},
)
],
),
),
);
}
}
class RoundedInputField extends StatelessWidget {
final IconData icon;
final FormFieldValidator<String> validate;
final String labelText;
final GlobalKey<FormFieldState> formFieldKey;
// (before flutter 2.0) drop `required`
const RoundedInputField({
Key? key,
required this.formFieldKey,
required this.labelText,
required this.icon,
required this.validate,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextFormField(
key: formFieldKey,
validator: validate,
decoration: InputDecoration(
icon: Icon(
icon,
color: Colors.blue,
),
labelText: labelText,
),
);
}
}
所以,最后我得到了解決方案。 在這里它完美地工作。
TextFormField 小部件
import 'package:attendance_system_app/text_field_container.dart';
import 'package:flutter/material.dart';
class RoundedInputField extends StatelessWidget {
final String hintText;
final IconData icon;
final ValueChanged<String> onChanged;
final TextEditingController controller;
final double fontsize;
final FormFieldValidator<String> validate;
final String errortext;
final String labelText;
final GlobalKey<FormFieldState> formFieldKey;
//final onsaved;
const RoundedInputField({Key key,this.labelText, this.formFieldKey, this.errortext,this.hintText, this.icon,this.validate, this.onChanged,this.controller,this.fontsize})
: super(key: key);
@override
Widget build(BuildContext context) {
return TextFormField(
decoration: InputDecoration(
labelText: labelText,
fillColor: Colors.blue[50],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(29.0),
),
// errorBorder:
// OutlineInputBorder(borderSide: BorderSide(color: Colors.purple)),
// focusedErrorBorder:
// OutlineInputBorder(borderSide: BorderSide(color: Colors.purple)),
// errorStyle: TextStyle(color: Colors.purple),
),
//controller: controller,
validator: validate,
controller: controller,
maxLength: 5,
//onSaved: (String ?onsaved);
);
//TextEditingController namecontroller = new TextEditingController();
//return TextFieldContainer(
// child: TextFormField(
// key: formFieldKey,
// onChanged: onChanged,
// cursorColor: Colors.black,
// style: TextStyle(fontSize: 16),
// controller: TextEditingController(),
// validator: validate,
// obscureText: true,
// decoration: InputDecoration(
// icon: Icon(
// icon,
// color: Colors.blue,
// ),
// hintText: hintText,
// border: InputBorder.none,
// //labelText: labeltext
// errorText: errortext,
// labelText: labelText,
// ),
// ),
//);
}
}
在這里你可以調用小部件。
class JafPersonals extends StatefulWidget {
@override
_JafPersonalState createState() => _JafPersonalState();
}
class _JafPersonalState extends State<JafPersonals> {
TextEditingController _applicantName=new TextEditingController();
TextEditingController _fatherName=new TextEditingController();
final GlobalKey<FormState> _formkey=GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return new Scaffold(
drawer: new AdminDrawerCode(),
appBar: AppBar(
title: Image.asset("assets/image/company_logo.png",height: 140,width: 280,
),
//automaticallyImplyLeading: false,
backgroundColor: Colors.white,
iconTheme: IconThemeData(color: Colors.blue,size: 20),
//leading: new Icon(Icons.menu,color: Colors.blue,),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.notifications,
color: Colors.blue,
size:26
),
onPressed: () {
// do something
},
)
],
),
body: Form(
key: _formkey,
//autovalidateMode: AutovalidateMode.onUserInteraction,
child: ListView(
padding: EdgeInsets.all(16),
children: [
Text(" Employee Bio Data",style: TextStyle(fontSize: 30,fontWeight: FontWeight.bold,color: Colors.blue[900])),
SizedBox(height: 20,),
Text(" Personal data",style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold,color: Colors.blue[900])),
SizedBox(height: 20,),
RoundedInputField(labelText: 'Applicant name',controller: _applicantName,
validate: (value) {
if (value.length < 4) {
return 'Enter at least 4 characters';
} else {
return null;
}
},),
SizedBox(height: 10),
RoundedInputField(labelText: 'Father name',controller: _applicantName,
validate: (value) {
if (value.length < 4) {
return 'Enter at least 4 characters';
} else {
return null;
}
},),
RoundedButton(text: 'Submit',
press: (){
final isvalid=_formkey.currentState.validate();
if(isvalid){
_formkey.currentState.save();
Navigator.push(context, MaterialPageRoute(builder: (context)=>JafFamily()));
}
},)
]
)
));
}
}
這段代碼解決了我的問題。 編碼快樂!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.