Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

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

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*'.

question from:https://stackoverflow.com/questions/65540707/why-are-async-getters-supported-but-async-setters-not-in-dart-language

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...