08.Flutter - Multi Child Layout Widget [ Part 2 ]


Flex


Flex Widget mirip dengan Widget Row dan Column, hanya widget flex bisa meletakkan komponen arah vertikal dan horizontal, untuk melakukannya kita cukup mengatur mainAxis-nya, perhatian contoh berikut:


Pada contoh diatas, app yang kita buat menggunakan widget Flex untuk konten utamanya, dimana isinya adalah tiga buah persegi panjang, pada bagian atas terdapat tombol untuk meletekaan komponen secara horizontal dan vertikal, kemudian pada tombol disebelahnya untuk mengganti nilai dari alignment dari main axis.

Berikut adalah kode programmnya.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomeWidget(title: 'Multi Layout Widget 2'),
    );
  }
}

class HomeWidget extends StatefulWidget {
  HomeWidget({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomeWidgetState createState() => _MyHomeWidgetState();
}

class _MyHomeWidgetState extends State<HomeWidget> {
  List<MainAxisAlignment> _alignments = [
    MainAxisAlignment.start,
    MainAxisAlignment.end,
    MainAxisAlignment.center,
    MainAxisAlignment.spaceBetween,
    MainAxisAlignment.spaceEvenly,
    MainAxisAlignment.spaceAround,
  ];

  List<String> _alignmentText = [
    "Start",
    "End",
    "Center",
    "Space Between",
    "Space Evenly",
    "Space Around",
  ];

  bool _vertical = true;
  int _alignmentIndex = 0;

  RawMaterialButton redButton = RawMaterialButton(
    onPressed: () {},
    elevation: 2.0,
    fillColor: Colors.red,
  );

  RawMaterialButton greenButton = RawMaterialButton(
    onPressed: () {},
    elevation: 2.0,
    fillColor: Colors.green,
  );

  RawMaterialButton blueButton = RawMaterialButton(
    onPressed: () {},
    elevation: 2.0,
    fillColor: Colors.blue,
  );

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.rotate_90_degrees_ccw),
            tooltip: 'Direction',
            onPressed: () {
              setState(() {
                _vertical = !_vertical;
              });
            },
          ),
          Padding(
            padding: EdgeInsets.only(top: 20.0),
            child: Text(_vertical ? "Vertical" : "Horizontal"),
          ),
          IconButton(
            icon: Icon(Icons.aspect_ratio),
            tooltip: 'Main Axis',
            onPressed: () {
              setState(() {
                _alignmentIndex++;
                if (_alignmentIndex >= _alignments.length) {
                  _alignmentIndex = 0;
                }
              });
            },
          ),
          Padding(
            padding: EdgeInsets.only(top: 20.0),
            child: Text(_alignmentText[_alignmentIndex]),
          ),
          Padding(
            padding: EdgeInsets.all(10.0),
          )
        ],
      ),
      body: Flex(
        direction: _vertical ? Axis.vertical : Axis.horizontal,
        mainAxisAlignment: _alignments[_alignmentIndex],
        children: <Widget>[
          redButton, greenButton, blueButton
        ],
      ),
    );
  }
}


ListView

Widget ListView mirip dengan flex widget dimana ListView bisa meletakkan komponen secara vertikal dan horizontal, perbedaan antar keduanya adalah ListView langsung menyediakan scrolling, perhatikan contoh berikut ini:


Geser layar ke kanan untuk melihat isi secara keseluruhan, berikut adalah kode programmnya.

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

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

class MyListApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'Horizontal List App';
    // TODO: implement build
    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: Container(
          margin: EdgeInsets.symmetric(vertical: 20.0),
          child: ListView(
            scrollDirection: Axis.horizontal,
            children: <Widget>[
              Container(
                width: 160.0,
                color: Colors.red,
              ),
              Container(
                width: 160.0,
                color: Colors.green,
              ),
              Container(
                width: 160.0,
                color: Colors.blue,
              ),
              Container(
                width: 160.0,
                color: Colors.yellow,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

List Tile


ListTile berisi satu sampai tiga baris (leading, title, trailing) Text yang secara opsional berisi widget icon atau widget lainnya misalnya checkboxes, dengan demikian kita bisa membuat wiget Text di tengah dan widget icon, checkboxes disisi kanan dan kirinya, perhatikan contoh berikut:


Berikut adalah kode programmnya:

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

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

class MyListApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'Horizontal List App';

    //ListTile
    final ListTile listTile1 = ListTile(
      leading: Icon(Icons.account_box),
      title: Text('Setting Account'),
      trailing: Icon(Icons.settings),
      onTap: () {},
      
    );
    // TODO: implement build
    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: ListView(
          children: <Widget>[
            listTile1
          ],
        )
      ),
    );
  }
}

Stack

Widget Stack Layout berguna untuk meng-overlay kumpulan dari widget, Stack Widget dapat kita analogikan sepertu tumpukan kartu, setiap child dari Widget Stack Layout adalah diposisikan atau tidak diposisikan, Positioned children adalah child widget yang dibungkus widget Positioned yang paling sedikit memiliki property yang tidak boleh null.

Stack menampilkan children widgetnya dengan urutan child pertama berada di bawah (bottom), jika kita ingin mengganti urutan dari peletakan child widget ini, kita dapat membuat ulang stack dengan children di urutan baru, dalam hal ini, pastikan setiap anak memiliki key untuk mencegahnya dari dibuat ulang (rebuilt) setiap kali.



import 'package:flutter/material.dart';

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

class StackApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomeWidget(title: 'Card Layout'),
    );
  }
}

class HomeWidget extends StatefulWidget {
  HomeWidget({Key key, this.title}) : super(key: key);
  final String title;

  final FirstWidget _firstWidget = FirstWidget(key: ObjectKey("firstwidget"));

  final SecondWidget _secondWidget =
      SecondWidget(key: ObjectKey("secondwidget"));

  @override
  _HomeWidgetState createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
  bool _changePage = false;

  void _tooglePage() {
    setState(() {
      _changePage = !_changePage;
    });
  }

  @override
  Widget build(BuildContext context) {
    //List Page
    List<Widget> _childWidget = _changePage
        ? [widget._firstWidget, widget._secondWidget]
        : [widget._firstWidget];

    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('Card Layout'),
      ),
      body: Stack(
        key: ObjectKey("stack"),
        children: _childWidget,
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _tooglePage,
        label: Text('Pages...'),
        icon: Icon(Icons.cached),
      ),
    );
  }
}

class FirstWidget extends StatelessWidget {
  FirstWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Text(
            'This is Frist Widget',
            style: TextStyle(fontSize: 30.0),
          ),
        ],
      ),
      color: Colors.grey,
    );
  }
}

class SecondWidget extends StatelessWidget {
  SecondWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Text('Second Widget', style: TextStyle(fontSize: 24.0)),
          Text('Using Stack', style: TextStyle(fontSize: 24.0)),
          Text('Like Card', style: TextStyle(fontSize: 24.0)),
        ],
      ),
      color: Colors.green,
    );
  }
}
08.Flutter - Multi Child Layout Widget [ Part 2 ] 08.Flutter - Multi Child Layout Widget [ Part 2 ] Reviewed by jc on August 08, 2019 Rating: 5

No comments:

Powered by Blogger.