asynchronous - 从 Dart 中的构造函数调用异步方法

标签 asynchronous constructor dart

假设 Dart 中 MyComponent 的初始化需要向服务器发送 HttpRequest。是否可以同步构造一个对象并推迟“真正的”初始化直到响应返回?

在下面的示例中,直到打印“done”后才会调用 _init() 函数。可以解决这个问题吗?

import 'dart:async';
import 'dart:io';

class MyComponent{
  MyComponent() {
    _init();
  }

  Future _init() async {
    print("init");
  }
}

void main() {
  var c = new MyComponent();
  sleep(const Duration(seconds: 1));
  print("done");
}

输出:

done
init

最佳答案

处理这个问题的最佳方法可能是使用工厂函数,它调用私有(private)构造函数。

在 Dart 中,私有(private)方法以下划线开头,并且“附加”构造函数需要采用 ClassName.constructorName 形式的名称,因为 Dart 不支持函数重载。这意味着私有(private)构造函数需要一个以下划线开头的名称(在下面的示例中为MyComponent._create)。

import 'dart:async';
import 'dart:io';

class MyComponent{
  /// Private constructor
  MyComponent._create() {
    print("_create() (private constructor)");

    // Do most of your initialization here, that's what a constructor is for
    //...
  }

  /// Public factory
  static Future<MyComponent> create() async {
    print("create() (public factory)");

    // Call the private constructor
    var component = MyComponent._create();

    // Do initialization that requires async
    //await component._complexAsyncInit();

    // Return the fully initialized object
    return component;
  }
}

void main() async {
  var c = await MyComponent.create();

  print("done");
}

这样,就不可能意外地从类中创建未正确初始化的对象。唯一可用的构造函数是私有(private)的,因此创建对象的唯一方法是使用工厂,它执行正确的初始化。

关于asynchronous - 从 Dart 中的构造函数调用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38933801/

相关文章:

dart - 您应该将dart源代码放在现有的服务器端Web项目中的什么位置?

javascript - async await Promise 用法永远阻塞等待

javascript - 如何找出一个对象是否是javascript中的数组?

flutter - 给定的podspec `FlutterToast`的名称与预期的 `fluttertoast`颤音不匹配

c++ - 为什么我们不能在构造函数初始化列表中初始化静态变量,但我们可以在构造函数体中

c# - 每次调用构造函数时,如何使我的 C# 随机数生成器发生变化?

flutter - Flutter:ReorderableListView更改项目宽度,并忽略圆角边框

javascript - 如果在 Promise 链中的某个点抛出错误,它是否会自动沿着链向下传播?

c# - Metro - 编写异步 c# 操作并从 javascript 调用

c# - MEF 插件架构的即发即弃方法