🎃

Flutterでon/offのswitchボタンを実装

2022/01/29に公開2

パターン1 Androidぽいやつ

SwitchListTile()を使う。

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

class MyApp extends StatelessWidget {
  const MyApp({
    required this.title,
    required this.value,
    required this.onChanged,
  });
  
  final bool title;
  final bool value;
  final void Function(bool)? onChanged;
  
  
  Widget build(BuildContext context) {
    return SwitchListTile(
      title: const Text('Lights'),
      value: value,
      onChanged: onChanged,
      secondary: const Icon(Icons.lightbulb_outline),
    );
  }
}

パターン2 IPhoneぽいやつ

CupertinoSwitch()を使う。

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

class CupertinoSwitchTile extends StatelessWidget {
  const CupertinoSwitchTile({
    required this.title,
    required this.value,
    required this.onChanged,
  });
  
  final bool title;
  final bool value;
  final void Function(bool)? onChanged;
  
  
  Widget build(BuildContext context) {
    return ListTile(
      leading: null,
      title: Text(title),
      trailing: CupertinoSwitch(
        value: value,
        onChanged: onChanged,
      ),
    );
  }
}

参考

https://api.flutter.dev/flutter/material/SwitchListTile-class.html
https://api.flutter.dev/flutter/cupertino/CupertinoSwitch-class.html

Discussion

ashdikashdik

今更かもですが、 SwitchListTile.adaptive で両者OS最適なスイッチを表示することができますよ 👍

shinriyoshinriyo

Text に渡すのはString型です。bool型ではありません。