🍏
CupertinoSwitch class
Note(ノート)
公式の解説を翻訳しております。
iOSスタイルのスイッチ。
1つの設定のオン/オフを切り替えるために使用する。
スイッチ自体はトグル状態を保持しません。その代わりに、スイッチのトグル状態が変更されると、ウィジェットは onChanged コールバックを呼び出します。スイッチを使うほとんどのウィジェットは、onChanged コールバックをリッスンして、新しい値でスイッチを再構築し、スイッチの見た目を更新します。
example
全体のコードは以下のようになります。
CupertinoPageScaffoldを2個書いてたので削除しました🧹
main.dart
import 'package:flutter/cupertino.dart';
/// Flutter code sample for [CupertinoCheckbox].
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('CupertinoCheckbox Example'),
),
child: Center(child: CupertinoSwitchExample()),
);
}
}
class CupertinoSwitchExample extends StatefulWidget {
const CupertinoSwitchExample({super.key});
State<CupertinoSwitchExample> createState() => _CupertinoSwitchExampleState();
}
class _CupertinoSwitchExampleState extends State<CupertinoSwitchExample> {
bool switchValue = true;
Widget build(BuildContext context) {
return Center(
child: CupertinoSwitch(
// This bool value toggles the switch.
value: switchValue,
activeTrackColor: CupertinoColors.darkBackgroundGray, // 色を変更できる
onChanged: (bool? value) {
// This is called when the user toggles the switch.
setState(() {
switchValue = value ?? false;
});
},
),
);
}
}
Que(きっかけ)
Flutter公式の動画を見て、
「iOSネイティブのトグルスイッチをお探しですか? CupertinoSwitchを検討してください」
「Appleのヒューマンガイドインターフェースガイドラインによると小さい画面の場合や特定のコントロールにユーザーの注意を引きたい場合にスイッチを使用することを推奨しています」
」
気になり試してみました。
デフォルトだとオンの時は緑色でオフの時は白色ですが、activeTrackColor
を使用して色を変更することができます。
Summary(要約)
checkboxと同じように、bool型の変数を定義して状態を更新すると、スイッチのON/OFFの切り替えができます。
bool型の状態変数であるswitchValueを定義する。
onChanged callBackの中で、setState()
を実行する。
Discussion