Flutter Use Conditional Statement in Child Widget Container Center

There are so much conditions in mobile application development where developer wants to control which widget he wants to display on certain condition. These type of functionality is called as Controlling widgets using conditional statements. There are several type of conditional statement is present in languages like If-Else, nested If-Else and Switch case statement. So far we cannot directly use any conditional statement in Widget build return code but using custom widget build method we can easily Flutter Use Conditional Statement in Child Widget Container widget, Center widget and any other widgets.

What we are doing in this tutorial:

We are creating custom Widget in our class and putting a If-Else conditional statement in our Widget. We are checking the device OS name using Platform package class. We would call this Widget in Center widget directly in Widget build area.

Contents in this project Flutter Use Conditional Statement in Child Widget Container Center Android iOS Example Tutorial:

1. Import material.dart and dart:io package in your app’s main.dart file.

2. Creating void main runApp() method and call our main MyApp class here.

3. Creating our main Root View class named as MyApp extends StatelessWidget.

4. Creating a Custom Widget named as _detectOS() using Widget keyword. The Widget keyword would enable a complete View Widget interface for flutter app and we can directly pass the widget name in any child attribute of Container, Center, Row, Column or any other widget. In this widget we would check the Operating system of mobile device using Platform package. If the device is Android then it would display the Android Device OS Detected text and if the device is iOS then it will display the iOS Device OS Detected text.

5. Creating Widget Build are in MyApp class and we would define the Center widget inside Scaffold widget. We would call the _detectOS() widget as Child of Center widget.

6. Complete source code for main.dart file:

Screenshot in Android device:

Flutter Use Conditional Statement in Child Widget Container Center

Screenshot in iOS device:

Leave a Reply

Your email address will not be published. Required fields are marked *