Search code examples
fluttertextfield

Flutter textform feild validation error Closure(String?)=>dynamic from Function mobileNumber static must has 10 characters


I am getting this weird error message when the mobile number is validation failed

Closure(String?)=>dynamic from Function mobileNumber static must has 10 characters

in this, this is the expected output mobileNumber static must has 10 characters but I'm getting it with this Closure(String?)=>dynamic from Function

i tried removing the static then I m unable to call it, this is the full code

static mobileNumber(String? txt) {
    if (txt == null || txt.isEmpty) {
      var mobileNumber = 'Mobile Number';
      return "Invalid $mobileNumber!";
    }
    print(txt.length);
    if (txt.length != 10) {
      return "$mobileNumber must has 10 characters";
    }
    if (!txt.contains(RegExp(r'[0-9]'))) {
      return "$mobileNumber must has digits";
    } else {}
  }

Solution

  • It's a variable name/scope conflict.
    You are using the same name mobileNumber for the function and same name inside the function.

    The inner variable 'mobileNumber' is only created inside the if statement

    if (txt == null || txt.isEmpty) {
          var mobileNumber = 'Mobile Number';
          return "Invalid $mobileNumber!";
        }
    

    Outside the if variable, mobileNumber is a function static mobileNumber... Change your code to something like this

    static mobileNumber(String? txt) {
          var mobileNumberStr = 'Mobile Number';
        if (txt == null || txt.isEmpty) {
          return "Invalid $mobileNumberStr!";
        }
        print(txt.length);
        if (txt.length != 10) {
          return "$mobileNumberStr must has 10 characters";
        }
        if (!txt.contains(RegExp(r'[0-9]'))) {
          return "$mobileNumberStr must has digits";
        } else {}
      }