| |

Flutterの練習3-2:Widget集を作成

ChatGTP先生にFlutterはWidgetが複雑に組み合わせられているので、可読性を上げる方法について聞いたところ、Widgetを別ファイルにすることを勧められました。
Flutterのサンプルプログラムにボタンなどを追加した際に、lib/widget/の中にmy_buttons.dartとmy_row_column.dartを作成し、その中にWidgetを整理しました。こちらをご参照
これから、このWidgetをマイWidget集として充実させていこうと思います。

=my_buttons.dart=
import 'package:flutter/material.dart';

class MyFloatingActionButton extends StatelessWidget {
  final Color color;
  final IconData icon;
  final String tooltip;
  final VoidCallback onPressed;

  // プロパティを受け取るコンストラクタ
  const MyFloatingActionButton({
    super.key,
    required this.color,
    required this.icon,
    required this.tooltip,
    required this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: onPressed, // 呼び出し元で指定した関数を実行
      backgroundColor: color, // ボタンの背景色
      tooltip: tooltip, // ツールチップ
      child: Icon(icon), // ボタンのアイコン
    );
  }
}

=main.dartの呼び出し部分=
import 'widget/my_buttons.dart' as mbtn;
・
・
      // #region FloatingActionButton
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          const SizedBox(width: 30),
          mbtn.MyFloatingActionButton(
            color: Colors.pink,
            icon: Icons.remove,
            onPressed: _decrementCounter,
            tooltip: 'Decrement',
          ),
          const Spacer(),
          mbtn.MyElevatedButton(
              name: "初期化",
              tooltip: "Reset",
              onPressed: _initializeCounter,
              fontSize: 20),
          const Spacer(),
          mbtn.MyFloatingActionButton(
            color: Colors.green, // 背景色
            icon: Icons.add, // アイコン
            tooltip: 'Increment', // ツールチップ
            onPressed: _incrementCounter, // 実行する関数
          ),
        ],
      ), // This trailing comma makes auto-formatting nicer for build methods.
      // #endregion FloatingActionButton

importする際に、”as mbtn”を入れていますが、なくても大丈夫です。ただし、あった方がわかりやすいと思っています。
できたものはこちら

類似投稿

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

This site uses Akismet to reduce spam. Learn how your comment data is processed.