什么等同于 python with dart 中的语句

what is equivalent to python with statement in dart

例如,当使用 pyrogram 库启动电报客户端时,可以这样做:

with Client as app:
  app.do_something()

虽然不像 pyrogram,但 dart 中已经有一个 tdlib 包。 感谢有关此主题的任何帮助。


对于了解 Dart 但不了解 Python 的人,with 语句采用 上下文管理器 并在主体前后执行其部分代码被执行。上面的代码大致相当于

app = Client.__enter__()
app.do_something()
app.__exit__()

除了 app.__exit__() 保证被调用,即使 app.do_something() 引发异常。 __enter____exit__ 是由 Client 类型定义的两个方法,使其成为上下文管理器。

没有直接的 Dart 相当于 Python with 语句。但是,您可以使用以下模式来实现相同的行为:

void clientScope(void Function(Client) callback) {
  // Initialize your client
  final client = Client.initialize();

  // Acts as the body of a 'with' statement
  callback(client);

  // Perform any cleanup
  client.cleanup();
}

然后可以按以下方式使用:

clientScope((Client app) {
  app.doSomething();
});

为了健壮性,您还可以将 callback 包装在 try-catch-finally 中并在 finally 块中执行任何清理。