Flutter has a inbuilt class named as Platform which is used to get information about the current running environment on which the application is running like Android platform or iOS platform. There are two inbuilt method define in this class one is Platform.isAndroid used to detect platform operating system is Android. Second is Platform.isIOS used to detect platform operating system is iOS. The both platform method returns value in Boolean True False form. If they detect the OS then they return us in True. So in this tutorial we would Flutter Detect Device Platform is Android or iOS & Load Different Widget Example Tutorial.
Contents in this project Flutter Detect Device Platform is Android or iOS & Load Different Widget Example Tutorial:
1. Import material.dart package and Platform package in your app’s main.dart file.
1 2 |
import 'package:flutter/material.dart'; import 'dart:io' show Platform; |
2. Call our main MyApp class using void main runApp() method.
1 |
void main() => runApp(MyApp()); |
3. Create our main class MyApp extends with State less widget.
1 2 3 4 |
class MyApp extends StatelessWidget { } |
4. Create a Widget build function named as _detectWidget(). We have to use the Widget keyword to make a drawable widget using function. In this function we would detecting device OS version and according to that show the widget on screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Widget _detectWidget() { if (Platform.isAndroid) { // Return here any Widget you want to display in Android Device. return Text('Android Device Detected', style: TextStyle(fontSize: 22)); } else if(Platform.isIOS) { // Return here any Widget you want to display in iOS Device. return Text('iOS Device Detected', style: TextStyle(fontSize: 22)); } } |
5. Creating Widget build area in MyApp class and call our _detectWidget().
1 2 3 4 5 6 7 8 9 10 11 12 |
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Detect Device is Android or iOS') ), body: Center( child: _detectWidget() ) ) ); } |
6. Complete source code for main.dart file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import 'package:flutter/material.dart'; import 'dart:io' show Platform; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { Widget _detectWidget() { if (Platform.isAndroid) { // Return here any Widget you want to display in Android Device. return Text('Android Device Detected', style: TextStyle(fontSize: 22)); } else if(Platform.isIOS) { // Return here any Widget you want to display in iOS Device. return Text('iOS Device Detected', style: TextStyle(fontSize: 22)); } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Detect Device is Android or iOS') ), body: Center( child: _detectWidget() ) ) ); } } |
Screenshot in Android device: