Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter set validator required or not required

How set TextFormField required or not required?

Eg. If required parameter = true validator: (value) => value!.isEmpty ? ‘Required!’ : null,

if required parameter = false Not required

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Widget _textInput({controller, name, enable, autofocus, required}) {
    return Container(
      child: TextFormField(
        autofocus: autofocus,
        enabled: enable,
        cursorColor: Colors.black,
        controller: controller,
        decoration: InputDecoration(
          filled: true,
          fillColor: Colors.white,
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black45),
          ),

        //if  required true or false change 
        validator: (value) => value!.isEmpty ? 'Required!' : null,

      ),
    );
  }

>Solution :

First of all you need to define you variable with type in constructor for example required should be like this bool required, then you can do this:

Widget _textInput({controller, name, enable, autofocus,bool required}) {
    return Container(
      child: TextFormField(
        autofocus: autofocus,
        enabled: enable,
        cursorColor: Colors.black,
        controller: controller,
        decoration: InputDecoration(
          filled: true,
          fillColor: Colors.white,
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black45),
          ),
        ),
        validator: required?  (value) => value!.isEmpty ? 'Required!' : null : null,
      ),
    );
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading