Detecting the Current Platform – iOS or Android?

Last reviewed in July 2019 by Frank Treacy
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show TargetPlatform;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    var platform = Theme.of(context).platform;

    return MaterialApp(
      title: 'My Multiplatform App',
      home: Scaffold(
        appBar: AppBar(
          title: Text(platform == TargetPlatform.iOS ? 'iOS' : 'Android or other'),
        ),
      ),
    );
  }
}

Result on iPhone:

screenshot

Result on Android:

screenshot

While Platform.isIOS or Platform.isAndroid will work in emulators, there are two issues:

  • If you write this code in a widget, and call this widget from a parent widget whose Theme has a different target platform, the widget won’t properly inherit the parent widget’s platform (as Platform.isX is oblivious to the context)
  • In tests, the value is always TargetPlatform.android so we are not able to test iOS behavior in our app

Therefore, always use Theme.of(context).platform!

The best from the Flutter-verse in 3 minutes or less? Join Snacks!

Delivered twice monthly. No link walls. No spam. EVER.