Flutter LayoutBuilder Widget (original) (raw)

`import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks',

  // to hide debug banner
  debugShowCheckedModeBanner: false,
  theme: ThemeData(
    primarySwatch: Colors.green,
  ),
  home: HomePage(),
);

} }

class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), ), body: Container(

      /// Giving dimensions to parent Container
      /// using MediaQuery
      /// [container's height] = [(phone's height) / 2]
      /// [container's width] = [phone's width]
      height: MediaQuery.of(context).size.height * 0.5,
      width: MediaQuery.of(context).size.width,

      /// Aligning contents of this Container
      /// to center
      alignment: Alignment.center,

      child: LayoutBuilder(
        builder: (BuildContext ctx, BoxConstraints constraints) {
          
          // if the screen width >= 480 i.e Wide Screen
          if (constraints.maxWidth >= 480) {
            return Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8),
                  alignment: Alignment.center,
                  height: constraints.maxHeight * 0.5,
                  color: Colors.red,
                  child: Text(
                    'Left Part of Wide Screen',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8),
                  alignment: Alignment.center,
                  height: constraints.maxHeight * 0.5,
                  color: Colors.green,
                  child: Text(
                    'Right Part of Wide Screen',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
              ],
            );

          // If screen size is < 480
          } else {
            return Container(
              alignment: Alignment.center,
              height: constraints.maxHeight * 0.5,
              color: Colors.green,
              child: Text(
                'Normal Screen',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            );
          }
        },
      ),
    ),
  ),
);

} }

`