Home > Blockchain >  Validator issue: The argument type 'String? Function(String)' can't be assigned to th
Validator issue: The argument type 'String? Function(String)' can't be assigned to th

Time:09-04

  String? _validatename(String value) {
    final _nameExp = RegExp(r'^[A-Za-z] $');
    if (value.isEmpty) {
      return 'This field is required';
    } else if (!_nameExp.hasMatch(value)) {
      return 'Only arithmetical characters allowed';
    } else {
      return null;
    }
  }

I tried to add validator to TextFormField to check validity of data, when ElevatedButton is pressed. I think i did everything alright, but returns an issue. Terminal says it's because _namecontroller does not match to validator parameters

The argument type 'String? Function(String)' can't be assigned to the parameter type 'String? Function(String?)?'.

If i try to delete ? sign in String?, it returns another issue, so i don't know what to do

class _RegisterFormPageState extends State<RegisterFormPage> {
  final _namecontroller = TextEditingController();

  final _formkey = GlobalKey<FormState>();

  void dispose() {
    _namecontroller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formkey,
        child: ListView(
          padding: EdgeInsets.all(16.0),
          children: [
            SizedBox(height: 20),
            TextFormField(
              controller: _namecontroller,
              validator: _validatename,       // issue
            ),
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: ElevatedButton(
                  onPressed: _submitform,
                  child: Text('Submit')),
            )
          ],
        ),
      ),
    );
  }

  void _submitform() {
    if (_formkey.currentState!.validate()) {
      print('Name: ${_namecontroller.text}');
    }
  }

CodePudding user response:

The validator callback provides nullable string,

Change it like

  String? _validatename(String? value) {
String? _validatename(String? value) {
  final _nameExp = RegExp(r'^[A-Za-z] $');
  if (value == null) {
    return "got null";
  } else if (value.isEmpty) {
    return 'This field is required';
  } else if (!_nameExp.hasMatch(value)) {
    return 'Only arithmetical characters allowed';
  } else {
    return null;
  }
}

More about TextFormField

  • Related