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"); } }
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();//私有构造 }

浙公网安备 33010602011771号