はじめに
セグメントボタンの使い道としては 複数の選択肢から選択し、
- ビューを切り替える
- ソート順を切り替える
など、が挙げられます。
SegmentedButtonクラス
# コンストラクタ SegmentedButton({ Key? key, required List<ButtonSegment<T>> segments, required Set<T> selected, void onSelectionChanged(Set<T>)?, bool multiSelectionEnabled = false, bool emptySelectionAllowed = false, ButtonStyle? style, bool showSelectedIcon = true, Widget? selectedIcon })
- segmentsが選択肢です
- segmentsの各要素であるButtonSegmentのvalueが選択されたときに取得できる値です
- onSelectionChangedが選択されたときに実行される処理です
実装例
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'SegmentedButton', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({Key? key}): super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('SegmentedButton'), ), body: Container( color: Colors.grey, child: Center( child: SegmentedButton( segments: const <ButtonSegment<int>>[ ButtonSegment( value: 0, label: Padding( padding: EdgeInsets.all(4.0), child: Text('年'), ), ), ButtonSegment( value: 1, label: Text('月'), ), ], selected: const <int>{ 0 }, onSelectionChanged: (Set<int> newSelection) => print('$newSelection'), ), ), ) ); } }