n1ks
n1ks

Reputation: 2458

How can I detect if my Flutter app is running in the web?

I know that I can detect the operating system with Platform.isAndroid, Platform.isIOS, etc. but there isn't something like Platform.isWeb so how can I detect this?

Upvotes: 163

Views: 93516

Answers (7)

Andriy Antonov
Andriy Antonov

Reputation: 1510

A bit simpler (and more reliable) is to use defaultTargetPlatform

What you need is can be done like next:

  • use kIsWeb to check if it is a web
  • use defaultTargetPlatform to get the platform

Here is an example:

final isWebMobile = kIsWeb && (defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS);

Upvotes: 0

Anandh Krishnan
Anandh Krishnan

Reputation: 6022

Method 1

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

if(kIsWeb){
   
}else{

}

Blockquote

Metohd 2

Just use this package get: ^4.6.6

import 'package:get/get.dart';

You can use this to find web

bool isWeb = GetPlatform.isWeb;

For Others

 bool isMobile = GetPlatform.isMobile;
 bool isAndroid = GetPlatform.isAndroid;
 bool isiOS = GetPlatform.isIOS;
 bool isWeb = GetPlatform.isWeb;
 bool isWindows = GetPlatform.isWindows;
 bool isMac = GetPlatform.isMacOS;
 bool isLinux = GetPlatform.isLinux;
 bool isFusia = GetPlatform.isFuchsia;
 bool isDesktop = GetPlatform.isDesktop;

Upvotes: 3

Ali Bagheri
Ali Bagheri

Reputation: 3429

In dart:

bool kIsWeb = bool.fromEnvironment('dart.library.js_util');

src: https://api.flutter.dev/flutter/foundation/kIsWeb-constant.html

Upvotes: 1

mNouh
mNouh

Reputation: 321

you can use "kIsWeb" to do the job

 if(kIsWeb){
// DO SOMETHING
}else{
// DO ANOTHER THING
}

Upvotes: 11

Diego Sanchez
Diego Sanchez

Reputation: 1447

If you want to know what your OS is on the web, you can use

    String platform = "";
    if (kIsWeb) {
      platform = getOSInsideWeb();
    }

    String getOSInsideWeb() {
      final userAgent = window.navigator.userAgent.toString().toLowerCase();
      if( userAgent.contains("iphone"))  return "ios";
      if( userAgent.contains("ipad")) return "ios";
      if( userAgent.contains("android"))  return "Android";
    return "Web";
   }

Upvotes: 33

Westy92
Westy92

Reputation: 21335

There is a global boolean kIsWeb which can tell you whether or not the app was compiled to run on the web.

Documentation: https://api.flutter.dev/flutter/foundation/kIsWeb-constant.html

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

if (kIsWeb) {
  // running on the web!
} else {
  // NOT running on the web! You can check for additional platforms here.
}

Upvotes: 319

Deven
Deven

Reputation: 724

There is a code written Below to get OS/web where flutter is running...

if(kIsWeb)
   return Text("It's web");

else if(Platform.isAndroid){
     return Text("it's Android"); }

Upvotes: 17

Related Questions