Flutter – LayoutBuilder

Layoutbuilder is used to choose if the two child-widgets will use a row or a column layout.

A streamcontroller is used to communicate between the child-widgets.

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Photodesk Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Demo(),
    );
  }
}

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Layout Building in Row/Column'),
      ),
      body: LayoutBuilder(
        builder: (context, constraints) {
          if (constraints.maxWidth < 800) {
            return layout('column');
          } else {
            return layout('row');
          }
        },
      ),
    );
  }
}

Widget layout(String layoutType) {
  var _streamController = StreamController<String>.broadcast();

  List<Widget> myChildren = [
    Flexible(
      child: Container(
        color: Colors.black26,
        width: double.infinity,
        height: 500,
        //color: Colors.pink,
        child: Column(
          children: [
            ListTile(
              leading: Icon(Icons.people),
              title: Text('Svænd Bent'),
              onTap: () {
                _streamController.add('Svænd Bent');
              },
            ),
            ListTile(
              leading: Icon(Icons.my_location),
              title: Text('Yrsa Tusse'),
              onTap: () {
                _streamController.add('Yrsa Tusse');
              },
            ),
            ListTile(
              leading: Icon(Icons.landscape),
              title: Text('Thormod Fuss'),
              onTap: () {
                _streamController.add('Thormod Fussit');
              },
            ),
          ],
        ),
      ),
      flex: 2,
    ),
    Flexible(
      child: Container(
        padding: EdgeInsets.all(10),
        width: double.infinity,
        height: 500,
        color: Colors.black12,
        child: Center(
          child: StreamBuilder(
            stream: _streamController.stream,
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return CircularProgressIndicator();
              } else {
                return Text(
                  snapshot.data.toString(),
                  style: TextStyle(
                    fontSize: 20,
                  ),
                );
              }
            },
          ),
        ),
      ),
      flex: 4,
    ),
  ];

  print('Rebuilding layout');
  if (layoutType == 'row') {
    return Row(
      children: myChildren,
    );
  } else {
    return Column(
      children: myChildren,
    );
  }
}