Dart的另类用法

1.当不知道Future什么时候返回时

class AsyncOperation<T> {
  final Completer _completer = new Completer();

  Future doOperation() {
    _startOperation();
    return _completer.future; // Send future object back to client.
  }

  // Something calls this when the value is ready.
  void _finishOperation(T result) {
    _completer.complete(result);
  }

  // If something goes wrong, call this.
  void _errorHappened(error) {
    _completer.completeError(error);
  }

  void _startOperation() async{
    print("_startOperation:start");
    await Future.delayed(Duration(seconds: 3));
    // _finishOperation("result" as T);
    _errorHappened("error");
    print("_startOperation:end");
  }
}
View Code

 2.Dart中的单例

class Singleton {

  ///第一种:饿汉式
  static final Singleton _cache = Singleton._internal();
  factory Singleton.single() {
    return _cache;
  }

  ///第二种:懒加载
  static Singleton? _lazCache;
  factory Singleton.lazy(){
    return _lazCache ??= Singleton._internal();
  }

  Singleton._internal();//私有构造
}
View Code

 

posted @ 2025-01-13 19:47  呢哇哦比较  阅读(14)  评论(0)    收藏  举报