【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part67 Multi-child layout widgets

基礎 から 学ぶ Flutter 」という書籍で  学習 したことを ブログでアウトプットしていこうと思います。今回は ウィジェット編 ( part67 )です。

前回

【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part66 Multi-child layout widgets

引き続き、Multi-child layout widgetsについて学びます。

Multi-child layout widgets

IndexedStackウィジェット

IndexedStackウィジェットは複数のウィジェットをステートを保持しつつ切り替えることができるウィジェットです。

状態を維持しながら切り替えるなんて、自分で実装したらすごく大変そうですよね!

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

void main() {
  runApp(new MaterialApp(home: new MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _State();
  }
}

class _State extends State<MyApp> {
  int _index = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text('テスト中です。'),
      ),
      body: IndexedStack(
        index: _index,
        children: <Widget>[
          box(
            color: Colors.black,
          ),
          box(
            color: Colors.red,
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            if (_index == 0) {
              _index = 1;
            } else {
              _index = 0;
            }
          });
        },
      ),
    ));
  }

  Widget box(
      {double height = 50,
      double width = 50,
      Color color = Colors.green,
      String txt = "0"}) {
    return Container(
        margin: const EdgeInsets.all(2),
        height: height,
        width: width,
        color: color,
        child: Text(txt));
  }
}

ボタンをタップして_indexの値を切り替えているだけなのにウィジェットが切り替わっていますね!
これは便利です。

最後に

・・・ウィジェットが小さすぎましたね(笑う

今日はここまで!