如何在 Dart/Flutter 中实现内联接口而不是使用类?

Ric*_*ick 4 java interface dart flutter

有没有办法在 dart/flutter 中实现接口而无需使用类?

目前,我的实现方式是使用下面的代码

class _UserSignupInterface extends _SignupSelectUsernamePageState
    implements UserSignupInterface {
  @override
  void onSuccess() {
    _navigateToUserPage();
  }

  @override
  void onError() {
    setState(() {
      _isSignupClickable = true;
    });
  }
}

_attemptSignup() {
  UserSingleton userSingletonInstance = UserSingleton().getInstance();
  UserSignupInterface _userSignupInterface = _UserSignupInterface();

  UserSingleton().getInstance().user.username = _username;

  UserLoginController.attemptSignup(_userSignupInterface,
      userSingletonInstance.user, userSingletonInstance.userDetail, _groupID);
}
Run Code Online (Sandbox Code Playgroud)

但是,我想实现这些接口方法而不必使用类,就像在 java 中一样。类似于下面的代码。

UserController.attemptSignup(context, new UserSignupRequest() {
            @Override
            public void onSuccess(User user, UserDetail userDetail, Group group) {
                btnContinueWithFacebook.setEnabled(true);
                Intent intent = new Intent(context, ScoopActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

                progressBar.setVisibility(View.GONE);
                startActivity(intent);
            }

            @Override
            public void onFail() {
                Log.d(APP.TAG, "Signup request has failed");
                btnContinueWithFacebook.setEnabled(true);
                progressBar.setVisibility(View.GONE);
                /**
                 * TODO:: Notify user of signup attempt failure
                 */
            }
        }, user, userDetail, group_id);
Run Code Online (Sandbox Code Playgroud)

lrn*_*lrn 5

Dart 中没有这样的功能。为了实现接口,您必须声明一个类。

替代方案是定义 API 来接受单个函数而不是单个对象,或者声明一个辅助类,它将必要方法的行为作为构造函数参数。

例子:

class _UserSignupInterface extends _SignupSelectUsernamePageState
    implements UserSignupInterface {
  void Function(_UserSingupInterface self) _onSuccess;
  void Function(_UserSingupInterface self) _onError;
  _UserSignupInterface(this._onSuccess, this._onError);

  @override
  void onSuccess() { 
    _onSuccess(this);
  }

  @override
  void onError() {
    _onError(this);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以将其称为:

... _UserSignupInterface((self) { 
    self._navigateToUserPage();
}, (self) {
  self.setState(() {
    self._isSignupClickable = true;
  });
})
Run Code Online (Sandbox Code Playgroud)

诚然,它不如 Java 漂亮。