有没有办法在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);
}
但是,我想实现这些接口方法而不必使用类,就像我在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);
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);
}
}
然后你可以把它称为:
... _UserSignupInterface((self) {
self._navigateToUserPage();
}, (self) {
self.setState(() {
self._isSignupClickable = true;
});
})
诚然,它并不像Java那样漂亮。