FutureOr
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
Example
Consider the following Dart function example:
dartimport '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