The modifier async can not by applied to the body of a setter

寵の児 提交于 2021-02-05 09:48:48

问题


How can I use hashIt function in setter if editor gives this error

The modifier async can not by applied to the body of a setter

  Future<String> hashIt(String password) async {
    return await PasswordHash.hashStorage(password);
  }

  set hashPass(String pass) async { // error here
    final hash = await hashIt(pass);
    _hash = hash;
  }

compiller message: Error: Setters can't use 'async', 'async*', or 'sync*'.


回答1:


The reason a setter cannot be async is that an async function returns a future, and a setter does not return anything. That makes it highly dangerous to make a setter async because any error in the setter will become an uncaught asynchronous error (which may crash your program). Also, being async probably means that the operation will take some time, but there is no way for the caller to wait for the operation to complete. That introduces a risk of race conditions. So, it's for your own protections.

If you need to do something asynchronous inside the setter anyway, perhaps log something after doing the actual setting, you have a few options.

The simplest is to just call an async helper function:

set foo(Foo foo) { 
  _foo = foo;
  _logSettingFoo(foo);
}
static void _logSettingFoo(Foo foo) async {
  try {
    var logger = await _getLogger();
    await logger.log("set foo", foo);
    logger.release();  // or whatever.
  } catch (e) {
    // report e somehow.
  }
}

This makes it very clear that you are calling an async function where nobody's waiting for it to complete.

If you don't want to have a separate helper function, you can inline it:

set foo(Foo foo) { 
  _foo = foo;
  void _logSettingFoo() async {
    ...
  }
  _logSettingFoo();
}

or even

set foo(Foo foo) { 
  _foo = foo;
  () async {
    ...foo...
  }();
}


来源:https://stackoverflow.com/questions/61497139/the-modifier-async-can-not-by-applied-to-the-body-of-a-setter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!