skip to Main Content

I’m making an app using Flutter which calculates motor vehicle tax.
enter image description here

It calculates it perfectly fine when I enter the cost of vehicle.
But I want to add a validation to it. When I don’t enter any cost of vehicle and keeps it empty and then click the calculate button, I want it show – please enter the cost.
How do I add this validation as this is not a form.

Here is the code of that part:

TextField(
            controller: costController,
            decoration: const InputDecoration(labelText: "Cost of Vehicle"),
            keyboardType: TextInputType.number,
            inputFormatters: <TextInputFormatter>[
              FilteringTextInputFormatter.digitsOnly
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          ElevatedButton(
              style: ElevatedButton.styleFrom(
                primary: Theme.of(context).primaryColor,
              ),
              onPressed: () {
                setState(() {
                  toPrint = calc(
                    dropDownValue!,
                    int.parse(costController.text),
                  ).toString();
                });
              },
              child: const Text("Calculate")),
          const SizedBox(
            height: 20,
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
            decoration: BoxDecoration(
                color: Colors.lightGreenAccent[100],
                border: const Border(
                  bottom: BorderSide(color: Colors.grey),
                )),
            child: Text("Tax :  $toPrint "),
          ),

2

Answers


  1. Wrap the column with a Form widget add avalidator to the textfield

    import 'package:flutter/material.dart';
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        const appTitle = 'Form Validation Demo';
    
        return MaterialApp(
          title: appTitle,
          home: Scaffold(
            appBar: AppBar(
              title: const Text(appTitle),
            ),
            body: const MyCustomForm(),
          ),
        );
      }
    }
    
    // Create a Form widget.
    class MyCustomForm extends StatefulWidget {
      const MyCustomForm({super.key});
    
      @override
      MyCustomFormState createState() {
        return MyCustomFormState();
      }
    }
    
    // Create a corresponding State class.
    // This class holds data related to the form.
    class MyCustomFormState extends State<MyCustomForm> {
      // Create a global key that uniquely identifies the Form widget
      // and allows validation of the form.
      //
      // Note: This is a GlobalKey<FormState>,
      // not a GlobalKey<MyCustomFormState>.
      final _formKey = GlobalKey<FormState>();
    
      @override
      Widget build(BuildContext context) {
        // Build a Form widget using the _formKey created above.
        return Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextField(
                controller: costController,
                decoration: const InputDecoration(labelText: "Cost of Vehicle"),
                keyboardType: TextInputType.number,
                inputFormatters: <TextInputFormatter>[
                  FilteringTextInputFormatter.digitsOnly
                ],
                // The validator receives the text that the user has entered.
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter some text';
                  }
                  return null;
                },
              ),
            ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    primary: Theme.of(context).primaryColor,
                  ),
                  onPressed: () {
                if (_formKey.currentState!.validate()) {
                    setState(() {
                      toPrint = calc(
                        dropDownValue!,                    int.parse(costController.text),
                      ).toString();
                    });
                   }
                  },
                  child: const Text("Calculate")),
              const SizedBox(
                height: 20,
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                decoration: BoxDecoration(
                    color: Colors.lightGreenAccent[100],
                    border: const Border(
                      bottom: BorderSide(color: Colors.grey),
                    )),
                child: Text("Tax :  $toPrint "),
              ),
            ],
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. Use Form Widget and Convert TextField to TextFormField like that.

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    class FormWidget extends StatefulWidget {
      const FormWidget({Key? key}) : super(key: key);
    
      @override
      State<FormWidget> createState() => _FormWidgetState();
    }
    
    class _FormWidgetState extends State<FormWidget> {
    
      final TextEditingController costController = TextEditingController();
      final _formKey = GlobalKey<FormState>();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          key: _formKey,
          body: Column(
            children: [
              Form(
                child: TextFormField(
                  validator: (value) {
                    if (value.isEmpty) {
                      return "Please enter the cost.";
                    }
                    return null;
                  },
                  controller: costController,
                  decoration: const InputDecoration(labelText: "Cost of Vehicle"),
                  keyboardType: TextInputType.number,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly
                  ],
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    primary: Theme.of(context).primaryColor,
                  ),
                  onPressed: () {
                    if(_formKey.currentState.validate()){
                      //do your setState stuff
                      setState(() {
                      });
                    }
    
                  },
                  child: const Text("Calculate")),
              const SizedBox(
                height: 20,
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                decoration: BoxDecoration(
                    color: Colors.lightGreenAccent[100],
                    border: const Border(
                      bottom: BorderSide(color: Colors.grey),
                    )),
                child: Text("Tax : "),
              ),
            ],
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search