flutterdartclosures

'(BuildContext, Exception) => void' is not a subtype of type '(BuildContext, Exception) => () => void'


I have a raised button that has a closure which executes a function in my AuthenticationProvider

RaisedButton(
  textColor: Theme.of(context).backgroundColor,
  onPressed: () => authenticationProvider.registerWithPhone(context, _phoneNumber, onFailed: _onRegistrationFailed),
  child: Text('Send'),
)

It pass a callback function that is in defined in the same widget

  void _onRegistrationFailed(BuildContext context, Exception exception)
  {
    showDialog(
      context: context,
      builder: (context) {
        return PlatformAlertDialog('test', 'test', 'test');
    });
  }

But I get the following error '(BuildContext, Exception) => void' is not a subtype of type '(BuildContext, Exception) => () => void'

This is the function that is being called by the raised button

  Future<void> registerWithPhone(BuildContext context, PhoneNumberModel phoneNumber,
      {VoidCallback onSuccess(BuildContext context), VoidCallback onFailed(BuildContext context, Exception exception)}) async {
    _status = AuthenticationStatus.Authenticating;
    notifyListeners();
    String localizedPhoneNumber = phoneNumber.toString();

    return await _authentication.verifyPhoneNumber(
        phoneNumber: localizedPhoneNumber,
        timeout: Duration(seconds: _phoneVerificationTimeout),
        verificationCompleted: (authCredential) => _verificationComplete(context, authCredential, onSuccess: onSuccess),
        verificationFailed: (authException) => _verificationFailed(context, authException, onFailed: onFailed),
        codeAutoRetrievalTimeout: (verificationId) => _codeAutoRetrievalTimeout(verificationId),
        codeSent: (verificationId, [code]) => _smsCodeSent(verificationId, [code]));
  }

So how should I pass a callback in a closure?


Solution

  • The actual issue is your type definition. You are expecting the VoidCallback to be returned while the function returns a void (nothing).

    Change:

    VoidCallback onFailed(BuildContext context, Exception exception)

    to

    void onFailed(BuildContext context, Exception exception)

    or

    void Function(BuildContext,Exception) onFailed

    The same for on onSuccess too.