Operative System detection 👀 (applied in multiple ways).

#FidelitasUniversity

Hello community!
I wanted to share this custom code for everyone to try out if you find it useful.

It basically detects the Operative System where the app is being run.

I first added a "On Page Load" trigger that will automatically call the code, as shown here:

Then, I also added a button where you can call that very same custom function and add modify the text shown previously (which in this case is the piece that says "Detectar mediante un botón":

Finally, I also wanted to try it out by using a BottomSheet passing the parameter to it. It works flawlessly as shown:

Since you need to add a dependency, we're going to create a new "Custom Action", otherwise it won't work. The code in question that you add is the following:

import 'package:flutter/foundation.dart';

String detectarOS() {
  if (defaultTargetPlatform == TargetPlatform.android) {
    return "El SO es Android.";
  } else if (defaultTargetPlatform == TargetPlatform.iOS) {
    return "El SO es iOS.";
  } else if (defaultTargetPlatform == TargetPlatform.fuchsia) {
    return "El SO es Fuchsia.";
  } else if (defaultTargetPlatform == TargetPlatform.linux) {
    return "El SO es Linux.";
  } else if (defaultTargetPlatform == TargetPlatform.macOS) {
    return "El SO es MacOS.";
  } else if (defaultTargetPlatform == TargetPlatform.windows) {
    return "El SO es Windows.";
  } else {
    return "No se pudo determinar el SO.";
  }
}

and the Custom Action should show like this:

Then, you can use your custom action as needed. The custom action will generate a variable that then can be used anywhere.

Please note that the strings are set in spanish, but you can completely change them to any language, and it'll work just fine.

1
1 reply