How to detect what platform a Flutter app is running on

Android? iOS? Web? MacOS? – With the growing number of supported build platforms, Flutter increases its value for developers who like to have only a single code base.
Also, this creates the necessity to make design decisions based on the platform it’s running on because the underlying APIs to access the hardware can vary.

Just to name a few things that are (not necessarily) available on the web platform:

  • Camera
  • Vibration
  • Push-Notifications
  • Acceleration sensor
  • Microphone

Flutter provides two different APIs that enables the caller to get to know more about the current platform: the kIsWeb constant that is part of the foundation library and the Platform class being part of the platform library.

The aim I have is to implement a class that provides an API that abstracts from these two quite low-level libraries. So let’s implement a class called PlatformInfo that has the public methods getCurrentPlatformType, isWeb, isAppOS and isDesktop. The first one should return an enum that is defined by us.

import 'dart:io';
import 'package:flutter/foundation.dart' show kIsWeb;

class PlatformInfo {
  bool isDesktopOS() {
    return Platform.isMacOS || Platform.isLinux || Platform.isWindows;
  }

  bool isAppOS() {
    return Platform.isMacOS || Platform.isAndroid;
  }

  bool isWeb() {
    return kIsWeb;
  }

  PlatformType getCurrentPlatformType() {
    if (kIsWeb) {
      return PlatformType.Web;
    }

    if (Platform.isMacOS) {
      return PlatformType.MacOS;
    }

    if (Platform.isFuchsia) {
      return PlatformType.Fuchsia;
    }

    if (Platform.isLinux) {
      return PlatformType.Linux;
    }

    if (Platform.isWindows) {
      return PlatformType.Windows;
    }

    if (Platform.isIOS) {
      return PlatformType.iOS;
    }

    if (Platform.isAndroid) {
      return PlatformType.Android;
    }

    return PlatformType.Unknown;
  }
}

enum PlatformType {
  Web,
  iOS,
  Android,
  MacOS,
  Fuchsia,
  Linux,
  Windows,
  Unknown
}

This gives us an easy possiblity to make decisions based on the OS or the group of underlying platforms:

Text _getMicrophoneSection() {
  if (PlatformInfo.isAppOS()) {
    return Text('Please tap the microphone button and then permit the usage');
  }

  return Text('If you have a microphone available, please turn it on');
}

The great thing about this class is: whenever Flutter enlarges its support portfolio, we can just extend it by adding a new enum member and an if-branch in the getCurrentPlatformType() method.
Until we’ve done that, nothing will break because we have a fallback enum member called PlatformType.Unknown.

If you like what you’ve read, feel free to support me:

🥗Buy me a salad

Leave a Comment