3

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".

3 Answers 3

4

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,
),
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, I provided some codes. Can you please check it out?
Edited @ShojiYamada
0

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

    
    }
  }

Comments

0

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)

1 Comment

Please provide an explanation of your answer so that the next user knows why this solution worked for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.