How to detect Apple User Agents in a Flutter web app?

Viewed 78

I'm making a cross-platform mobile app with Flutter targeting iOS, Android and Web. I want to show the Cupertino theme to users of Apple devices and the Material (3) theme to users of all other devices.

As for iOS and Android builds, I detect the OS using the Universal Platform library and present the corresponding theme, no problem with that. However, as for the Web builds, I would like to detect the OS using the User Agent string.

By "users of Apple devices" I mean users who open my app on either macOS, iOS or iPadOS (or any other OS by Apple I missed, if possible), regardless of their browser. I would also include users of other OSs who specifically changed their User Agent string to make it look like they're using an Apple device, as I think it's safe to assume that they would prefer (or at least expect) to see the Cupertino theme; and I would exclude those who did the opposite, for the same reasons.

What would be the best way to detect such "Apple device users" in my Flutter Web app via User Agent? Right now I'm inclined to just look for /Mac/ in the User Agent string, but I'm afraid of getting many false positives. Thank you!

1 Answers

Try this package from pub.dev: https://pub.dev/packages/web_browser_detect

This example is what you are looking for:

import 'package:web_browser_detect/web_browser_detect.dart';

void main() {
  final browser = Browser.detectFrom(userAgent: userAgent, vendor: vendor, appVersion: appVersion);

  print('${browser.browser} ${browser.version}');
}
Related