gpt4 book ai didi

dart - 阻塞直到字段初始化

转载 作者:行者123 更新时间:2023-12-03 03:44:22 24 4
gpt4 key购买 nike

尝试阻止 setter 中的执行,直到字段值更改为止,并​​且我知道它将在几微秒内更改,以演示我编写的问题:

import 'dart:async';

void main() {
new Timer.periodic(new Duration(seconds:1),(t)=>print(Store.x));
new Timer.periodic(new Duration(seconds:3),(t)=>Store.x='initialized');
}

class Store{
static String _x = null;
static set x(v) => _x=v;
static get x{
//how do i block here until x is initialized
return _x;
}
}

一个 while(x==null);导致stackoverflow,是否知道如何在setter中正确执行此操作?

基本上,我希望 setter 在初始化时返回值,因此永远不要返回null。

最佳答案

无法做到这一点。
Dart是单线程的。如果停止执行,则无法执行更新字段的代码。

如果您想要类似的东西,则需要切换到异步执行。

导入'dart:async';

void main() {
new Timer.periodic(new Duration(seconds:1),(t)=>print(Store.x));
new Timer.periodic(new Duration(seconds:3),(t)=>Store.x='initalized');
}

class Store{
static String _x = null;
static set x(v) => _x=v;
static Future<String> get x async {
while(x == null) {
await new Future.delayed(const Duration(milliseconds: 20),
}
return _x;
}
}

func someFunc() async {
var x = await new Store.x;
}

对于这种用例,我不会认为此 Future.delayed()是好的设计。它的实现方式应是 Store.x在值更改时触发事件或完成将来的操作。

关于dart - 阻塞直到字段初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30354354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com