【问题标题】:Flutter create own classFlutter 创建自己的类
【发布时间】:2018-10-12 04:34:45
【问题描述】:

我正在尝试创建一个包含特定身份验证过程内部方法的类

所以我创建了一个文件 MyAuthMethods.dart

class UserAuth {

  static int seconds = 10000000;
  static String username;
  static String password;
  static String key = "abc123";

  static Future<String> _generateAuthCode(seconds, username, password, key) async{
    var result = "something";
    print("Seconds: seconds, Username: username, Password: password, Key: key");

    return result;
  }

}

在我的表单 (FormScreen.dart) 上,有一个按钮 onPressed 来执行该功能

onPressed:(){
  UserAuth._generateAuthCode(UserAuth.seconds, "username", "password", UserAuth.key);
}

但它不起作用。它说:

error: The method '_generateAuthCode' isn't defined for the class 'UserAuth'.

我需要改变什么?

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    Dart 中没有 public、protected 和 private 之类的关键字。为了使变量或函数对类私有,变量或函数的名称需要以下划线开头(_)。没有下划线(_)的变量/函数是公开的。您已经定义了一个私有函数并访问了该私有函数。您可以通过公开函数来修复:为此,只需从函数中删除下划线,将其设为generateAuthCode

    class UserAuth {
    
      static int seconds = 10000000;
      static String username;
      static String password;
      static String key = "abc123";
    
      static Future<String> generateAuthCode(seconds, username, password, key) async{
        var result = "something";
        print("Seconds: seconds, Username: username, Password: password, Key: key");
    
        return result;
      }
    
    }
    

    【讨论】:

    • 去吧。对不起,但对飞镖很陌生。非常感谢。
    • @RaffaeleColleo 没问题。我也被这个卡住了。
    【解决方案2】:

    与 Java 不同,Dart 没有关键字 public、protected 和 private。如果标识符以下划线 (_) 开头,则它对其库是私有的。

    Libraries and visibility

    所以 _generateAuthCode 是你的类的私有方法,所以只有你不能访问。

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      相关资源
      最近更新 更多