2016-08-13 5 views
2

Dart의 MyComponent를 초기화하려면 서버에 HttpRequest를 전송해야한다고 가정 해 봅시다. 동 기적으로 객체를 구성하고 응답이 돌아올 때까지 '실제'초기화를 연기 할 수 있습니까?Dart의 구성 요소 생성자에서 비동기 메서드 호출

아래 예제에서는 "완료"가 인쇄 될 때까지 _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 
+0

정적 비동기 방식을 사용할 수 있습니까? – Ganymede

답변

1

생성자는 단지 클래스의 인스턴스를 리턴 할 수 그것은 (MyComponent)의 생성자이다. 요구 사항에 따라 지원되지 않는 Future<MyComponent>을 반환하는 생성자가 필요합니다.

class MyComponent{ 
    MyComponent(); 

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

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

또는 당신이 consturctor에서 초기화를 시작하고 기다리는 구성 요소의 사용자 수 :

당신에게 하나 같은 클래스의 사용자에 의해 호출 될 필요가 명시 적으로 초기화 방법을 확인해야합니다 초기화가 완료되었습니다. _doneFuture가 이미 즉시 await c.initializationDone 반환 완료되었을 때 미래를 먼저 완료 될 때까지

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"); 
} 

그렇지 않으면 기다립니다.

관련 문제