Flutter textform字段验证错误Closure(String?)=>dynamic from Function mobileNumber static必须有10个字符

kq0g1dla  于 2023-06-24  发布在  Flutter
关注(0)|答案(1)|浏览(179)

我得到这个奇怪的错误消息时,移动的号码验证失败
Closure(String?)=>dynamic from Function mobileNumber static must has 10 characters
在这里,这是预期的输出mobileNumber static must has 10 characters,但我用这个Closure(String?)=>dynamic from Function得到它
我试着删除静态,然后我无法调用它,这是完整的代码

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 {}
  }
s8vozzvw

s8vozzvw1#

这是一个变量名/作用域冲突。
您正在为函数使用相同的名称mobileNumber,并在函数内部使用相同的名称。
内部变量“mobileNumber”仅在if语句中创建

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

在if变量之外,mobileNumber是一个函数static mobileNumber...将代码改为如下所示

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 {}
  }

相关问题