乐闻世界logo
搜索文章和话题

What is the purpose of ` FutureOr `?

1个答案

1

FutureOr is a type in Dart that represents a variable which can be either a Future or a T. This type is particularly useful in Dart's asynchronous programming when a function or method might return an immediate value or a future value.

This type is primarily used in function return types to provide developers with more flexible APIs. For example, consider implementing a function that might return data directly from cache (an immediate value) or fetch data from the network (an asynchronous Future value). Using FutureOr as the return type effectively handles this scenario.

Example

Consider the following Dart function example:

dart
import 'dart:async'; // Simulated database query function Future<String> fetchDataFromDatabase() async { await Future.delayed(Duration(seconds: 2)); // Simulate network delay return "Database data"; } // Simulated function to fetch data from local cache String fetchDataFromCache() { return "Cache data"; } // Using FutureOr FutureOr<String> getData(bool fromCache) { if (fromCache) { return fetchDataFromCache(); } else { return fetchDataFromDatabase(); } } Future<void> main() async { print(await getData(true)); // Output: Cache data print(await getData(false)); // Output: Database data }

In this example, the getData function determines whether to return data directly from cache or asynchronously fetch data from the database based on the boolean value fromCache. The return type FutureOr<String> allows the function to return either a String value or a Future value. This design provides high flexibility, allowing the function to handle synchronous or asynchronous operations flexibly based on the situation.

2024年7月18日 20:06 回复

你的答案