maybeWhen<R> static method

R maybeWhen<R>({
  1. required R orElse(),
  2. R android()?,
  3. R fuchsia()?,
  4. R iOS()?,
  5. R linux()?,
  6. R macOS()?,
  7. R web()?,
  8. R windows()?,
})

Invokes the given function based on the current platform.

Example usage:

FunctionalPlatform.maybeWhen(
  android: () => print('Running on Android'),
  iOS: () => print('Running on iOS'),
  orElse: () => print('Running on other platform'),
);

The orElse function is required and will be called if no specific platform function is provided or if the current platform does not match any of the provided platform functions.

The optional platform-specific functions (android, fuchsia, iOS, linux, macOS, web, windows) will be called if the current platform matches the respective platform.

Returns the result of the invoked function.

Implementation

static R maybeWhen<R>({
  required R Function() orElse,
  R Function()? android,
  R Function()? fuchsia,
  R Function()? iOS,
  R Function()? linux,
  R Function()? macOS,
  R Function()? web, // IO is not available on Web.
  R Function()? windows,
}) {
  // To cover this line just run tests with `flutter test --platform chrome`.
  if (kIsWeb) return web?.call() ?? orElse(); // coverage:ignore-line

  return switch (defaultTargetPlatform) {
    TargetPlatform.android => android?.call() ?? orElse(),
    TargetPlatform.iOS => iOS?.call() ?? orElse(),
    TargetPlatform.macOS => macOS?.call() ?? orElse(),
    TargetPlatform.windows => windows?.call() ?? orElse(),
    TargetPlatform.linux => linux?.call() ?? orElse(),
    TargetPlatform.fuchsia => fuchsia?.call() ?? orElse(),
  };
}