How To Use Layout Builder Widget Using Flutter App

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

Similar to the Builder widget except that the framework calls the builder function at layout time and provides the parent widget's constraints. This is useful when the parent constrains the child's size and doesn't depend on the child's intrinsic size. The LayoutBuilder's final size will match its child's size.

How To Use Layout Builder Widget Using Flutter App

 Layout Builder Widget 
Complete Code For  Layout Builder Widget  In Flutter
main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.yellow[700],
          title: Text("Layout Builder Widget")),
      body: LayoutBuilder(
        builder: (context, constraints) {
          if (constraints.maxWidth > 600) {
            return _buildTwoContainers();
          } else {
            return _buildOneContainer();
          }
        },
      ),
    );
  }

  Widget _buildOneContainer() {
    return Center(
      child: Container(
        height: 200.0,
        width: 200.0,
        color: Colors.pink,
      ),
    );
  }

  Widget _buildTwoContainers() {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          Container(
            height: 200.0,
            width: 200.0,
            color: Colors.green,
          ),
          Container(
            height: 200.0,
            width: 200.0,
            color: Colors.pink,
          ),
        ],
      ),
    );
  }
}

Related Post