今天使用Future.delayed這個(gè)方法的時(shí)候發(fā)現(xiàn)第二個(gè)參數(shù)是FutureOr,然后吧,覺(jué)得沒(méi)什么大不了的只是一個(gè)普通類而已,但是用的時(shí)候發(fā)現(xiàn)了區(qū)別,測(cè)試代碼如下:
import 'dart:async';
main() {
test(FutureOr<String> computation()) {}
test(() async {
return "aa";
});
test(() {
return "abc";
});
}
看到?jīng)],test方法的參數(shù)是FutureOr<String>類型,但是我可以返回Future<String>也可以返回String,是不是對(duì)于平時(shí)使用java或者kotlin的人來(lái)說(shuō)比較奇怪?然后我們可以跳轉(zhuǎn)到FutureOr類里看一下這個(gè)類上面的文檔描述,會(huì)發(fā)現(xiàn)這么一段話,我選重要的貼一下
///A type representing values that are either `Future<T>` or `T`.
翻譯:這個(gè)類型相當(dāng)于`Future<T>` 或者 `T`
算了我比較懶。。。我全貼出來(lái)自己看吧
/// A type representing values that are either `Future<T>` or `T`.
///
/// This class declaration is a public stand-in for an internal
/// future-or-value generic type. References to this class are resolved to the
/// internal type.
///
/// It is a compile-time error for any class to extend, mix in or implement
/// `FutureOr`.
///
/// Note: the `FutureOr<T>` type is interpreted as `dynamic` in non strong-mode.
///
/// # Examples
/// ``` dart
/// // The `Future<T>.then` function takes a callback [f] that returns either
/// // an `S` or a `Future<S>`.
/// Future<S> then<S>(FutureOr<S> f(T x), ...);
///
/// // `Completer<T>.complete` takes either a `T` or `Future<T>`.
/// void complete(FutureOr<T> value);
/// ```
///
/// # Advanced
/// The `FutureOr<int>` type is actually the "type union" of the types `int` and
/// `Future<int>`. This type union is defined in such a way that
/// `FutureOr<Object>` is both a super- and sub-type of `Object` (sub-type
/// because `Object` is one of the types of the union, super-type because
/// `Object` is a super-type of both of the types of the union). Together it
/// means that `FutureOr<Object>` is equivalent to `Object`.
///
/// As a corollary, `FutureOr<Object>` is equivalent to
/// `FutureOr<FutureOr<Object>>`, `FutureOr<Future<Object>>` is equivalent to
/// `Future<Object>`.
簡(jiǎn)而言之,這個(gè)類型可以當(dāng)做Future<T>或者T類型,所以在有些時(shí)候要注意,在使用FutureOr<T>執(zhí)行任何有用的操作之前,通常需要檢查是否有Future<T>或明確的T。如果type參數(shù)是某個(gè)特定類型,如FutureOr<int> ,使用哪個(gè)測(cè)試無(wú)關(guān)緊要,是int還是Future<int>。 兩者都有效,因?yàn)檫@兩種類型是不相交的。
但是,如果值類型是Object或可能使用Object實(shí)例化的類型參數(shù),則兩個(gè)分支重疊。 Future<Object>本身實(shí)現(xiàn)了Object,因此是Object或者是T,其中T是一些可以用Object實(shí)例化的類型參數(shù),即使對(duì)象是future也會(huì)返回true。 相反,明確測(cè)試Future案例:
Future<T> logValue<T>(FutureOr<T> value) async {
if (value is Future<T>) {
var result = await value;
print(result);
return result;
} else {
print(value);
return value as T;
}
}
錯(cuò)誤用法示例:
Future<T> logValue<T>(FutureOr<T> value) async {
if (value is T) {
print(value);
return value;
} else {
var result = await value;
print(result);
return result;
}
}
在這個(gè)糟糕的示例中,如果您向它傳遞一個(gè)Future,它會(huì)錯(cuò)誤地將其視為一個(gè)簡(jiǎn)單的同步值。