dart - 阻塞直到字段初始化

标签 dart

尝试阻止 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/

相关文章:

android - 从 future 的 flutter 中返回一个列表

svg - 如何使用 Dart 向 SVG 动态添加线性渐变

firebase - Flutter:StreamBuilder中的项目(使用firebase实时数据库)随机排序

dart - 客户优化是什么意思?

flutter - 如何在连接器中连接多个模型(ScopedModel)

visual-studio-code - Flutter-为我的应用程序创建一个 android 模拟器

json - Flutter:如何下载Json文件到本地然后访问

dart - 在Dart PolymerElement中嵌套在另一个PolymerElement中

flutter - 我可以将对象作为参数传递给小部件吗

dart - 如何在 Dart 存储中获取所有对象