Reputation: 75
I have this simple calculator made in Flutter, my problem is I want to check if user inputted a string in a Text Field then (if true) display "Must enter valid number". How can I do this? I'm new to flutter so can someone help me?
I'm aware in using keyboard type as a number but that's not my task. I'm also aware for Text Field validation but that's not what I want, I need to display error message using a Text Widget.
These are my variables and controller
final TextEditingController fController = new TextEditingController();
final TextEditingController sController = new TextEditingController();
String errorMessage = "None";
String result = '0';
double num1, num2;
This is my addNum
void addNum() {
setState(() {
num1 = double.parse(fController.text);
num2 = double.parse(sController.text);
result = (num1 + num2).toString();
});
}
This is the onPressed
onPressed: () {
addNum();
if (result.contains('a') || result.contains('a')) {
setState(() {
errorMessage = "Invalid";
});
}
},
This is where I display the text
Text(
"Output: ${result.toString()}\n"
"Error: ${errorMessage.toString()}",
),
I'm getting an error "Invalid Double a".
Upvotes: 3
Views: 5914
Reputation: 1
Try to use controller , like this instead
Before Widget Build:
final _mycontroller = TextEditingController();
bool _validate = false;
@override
void dispose() {
_mycontroller.dispose();
super.dispose();
}
On Button:
onPressed(){
setState(){
_mycontroller2.text.contains("@")
? _validate = true
: _validate = false;
}}
On TextField:
TextField(
...
errorText: _validate ? "Insert a valid email": null)
Upvotes: 0
Reputation: 11
This is the right way to do this, you don't need to use a controller, remember to use the most simple and efficient code. Use stateFulWidget. This code generate the error message automatically.
String isEmpty(String value){
return value.isEmpty ? 'Required field' : null;
}
final _formKey = GlobalKey<FormState>();
return Form(
key: _formKey,
child: TextFormField(
decoration: InputDecoration(
hintText: 'Your Place holder here',
),
validator: isEmpty,
onSaved: (String value) {
_correctTextValue = value;
},
),
);
On your button onPressed() method put this:
_submit() async {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
// Your code here
}
}
Upvotes: 0
Reputation: 419
use https://api.flutter.dev/flutter/widgets/TextEditingController-class.html,
example of usage:
TextEditingController stringController = new TextEditingController();
String errorMessage;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
TextFormField(
controller: stringController,
),
FlatButton(
onPressed: () {
String a = stringController.text.trim();
if(a.isEmpty) {
//Put some code here for if string a is empty.
setState(() {
errorMessage = "Your error message";
});
}
}
),
Text(
errorMessage,
),
]
),
),
}
Try changing text outputs
Text(
"Output: " + result +
"\nError: " + errorMessage,
),
Upvotes: 4