[flutter] ボタンを押したら色やアイコンを切り替える

[flutter] ボタンを押したら色やアイコンを切り替える

flutterのElevatedButtonを押したら背景色やアイコンをトグルで切り替える方法です。

ボタンの状態(State)である背景色・アイコンを持つことになるため、 StatefulWidget を使用します。

NotificationButton.dart

import 'package:flutter/material.dart';

class NotificationButton extends StatefulWidget {
  @override
  _NotificationButtonState createState() => _NotificationButtonState();
}

class _NotificationButtonState extends State<NotificationButton> {
  bool isPressed = false;
  IconData icon = Icons.notifications;
  MaterialColor primaryColor = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton.icon(
      icon: Icon(
        this.icon,
        color: Colors.yellow,
      ),
      label: const Text('通知する'),
      style: ElevatedButton.styleFrom(
        primary: this.primaryColor,
        onPrimary: Colors.white,
      ),
      onPressed: () {
        this.isPressed = !this.isPressed;

        setState(() {
          this.icon =
              this.isPressed ? Icons.notifications_active : Icons.notifications;
          this.primaryColor = this.isPressed ? Colors.orange : Colors.blue;
        });
      },
    );
  }
}

 

プログラミングカテゴリの最新記事