Use Conditional Statement In Child Widget Using Flutter

admin_img Posted By Bajarangi soft , Posted On 12-10-2020

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.

Use Conditional Statement In Child Widget Using Flutter

Conditional Statement In Child Widget
Complete Code For Conditional Statement In Child Widget In Flutter
Main.dart

import 'package:flutter/material.dart';
import 'dart:io' show Platform;
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.lightGreen,
            title: Text("Use Conditional Statement in Child Widget"),
          ),
          body: CustomView()
      ),
    );
  }
}

class CustomView extends StatefulWidget {
  CustomViewWidget createState() => CustomViewWidget();
}
class CustomViewWidget extends State {
  Widget _detectOS() {
    if (Platform.isAndroid) {
      return Container(
          width: 150.00,
          color: Colors.orange,
          padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
          child: Text('Android Device OS Detected',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20, color: Colors.white)
          )
      );
    }
    else if (Platform.isIOS) {
      return Container(
          width: 150.00,
          padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
          color: Colors.blueAccent,
          child: Text('iOS Device OS Detected',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20, color: Colors.white))
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
        home: Scaffold(
          body: Center(
              child: _detectOS()
          ),
        )
    );
  }
}

 

Related Post