Home > Net >  Flutter set validator required or not required
Flutter set validator required or not required

Time:12-23

How set TextFormField required or not required?

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

if required parameter = false Not required

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,

      ),
    );
  }

CodePudding user response:

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,
      ),
    );
  }

CodePudding user response:

Just assign a enable bool anywhere in your class:

bool enable = true;


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),
          ),
        validator: (value) => enable? value!.isEmpty ? 'Required!' : null: null,   // you need to add another tertiary operator

      ),
    );
  }

Or you can also do:

validator: (value) { 
              if(enable){
                if(value!.isEmpty){
                  return 'Required!';
                }
                else{
                  return null;
                }
              }
              else{
                return null;
              }
              }

To ease things a bit

  • Related