Skip to content
Advertisement

How to implement interface in-line instead of using a class in Dart/Flutter?

Is there any way to implement an interface in dart/flutter without having to use a class?

Currently, how I implement it is with the code below

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);
}

However, I would like to implement these interface methods without having to use a class, just as I would in java. Something that would look like the code below.

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);

Advertisement

Answer

There is no such feature in Dart. In order to implement an interface, you have to declare a class.

The alternatives is to define the API to accept individual functions instead of a single object, or to declare a helper class which takes the behavior of the necessary methods as constructor arguments.

Example:

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);
  }
}

Then you can call it as:

... _UserSignupInterface((self) { 
    self._navigateToUserPage();
}, (self) {
  self.setState(() {
    self._isSignupClickable = true;
  });
})

It’s not as pretty as Java, admittedly.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement