从 Dart 中的组件构造函数调用异步方法 [英] Calling an async method from component constructor in Dart

查看:47
本文介绍了从 Dart 中的组件构造函数调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's assume that an initialization of MyComponent in Dart requires sending an HttpRequest to the server. Is it possible to construct an object synchronously and defer a 'real' initialization till the response come back?

在下面的示例中,_init() 函数在打印done"之前不会被调用.可以解决这个问题吗?

In the example below, the _init() function is not called until "done" is printed. Is it possible to fix this?

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

推荐答案

构造函数只能返回它是 (MyComponent) 的构造函数的类的实例.您的要求将需要构造函数返回不支持的 Future.

A constructor can only return an instance of the class it is a constructor of (MyComponent). Your requirement would require a constructor to return Future<MyComponent> which is not supported.

您要么需要创建一个需要由类的用户调用的显式初始化方法,例如:

You either need to make an explicit initialization method that needs to be called by the user of your class like:

class MyComponent{
  MyComponent();

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

void main() async {
  var c = new MyComponent();
  await c.init();
  print("done");
}

或者您在构造函数中开始初始化并允许组件的用户等待初始化完成.

or you start initialization in the consturctor and allow the user of the component to wait for initialization to be done.

class MyComponent{
  Future _doneFuture;

  MyComponent() {
    _doneFuture = _init();
  }

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

  Future get initializationDone => _doneFuture
}

void main() async {
  var c = new MyComponent();
  await c.initializationDone;
  print("done");
}

_doneFuture 已经完成时 await c.initializationDone 立即返回,否则它等待 future 首先完成.

When _doneFuture was already completed await c.initializationDone returns immediately otherwise it waits for the future to complete first.

这篇关于从 Dart 中的组件构造函数调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆