Files
pipelines/app/lib/features/terminal/terminal_menu.dart
T

91 lines
2.6 KiB
Dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// One choice of a [TerminalMenuButton].
class TerminalChoice<T> {
const TerminalChoice(this.value, this.label, {this.checked, this.key});
final T value;
final String label;
/// Non-null draws the choice as a checkable item.
final bool? checked;
final Key? key;
}
/// An icon button opening the host's menu: a Material popup menu, or a
/// Cupertino action sheet with Cancel.
class TerminalMenuButton<T> extends StatelessWidget {
const TerminalMenuButton({
super.key,
required this.cupertino,
required this.label,
required this.icon,
required this.cupertinoIcon,
required this.choices,
required this.onSelected,
});
final bool cupertino;
final String label;
final IconData icon;
final IconData cupertinoIcon;
final List<TerminalChoice<T>> choices;
final ValueChanged<T> onSelected;
@override
Widget build(BuildContext context) {
if (!cupertino) {
return PopupMenuButton<T>(
tooltip: label,
icon: Icon(icon),
onSelected: onSelected,
itemBuilder: (_) => [
for (final choice in choices)
choice.checked == null
? PopupMenuItem<T>(
key: choice.key,
value: choice.value,
child: Text(choice.label),
)
: CheckedPopupMenuItem<T>(
key: choice.key,
value: choice.value,
checked: choice.checked!,
child: Text(choice.label),
),
],
);
}
return CupertinoButton(
padding: const EdgeInsets.symmetric(horizontal: 8),
onPressed: () => _sheet(context),
child: Icon(cupertinoIcon, semanticLabel: label),
);
}
Future<void> _sheet(BuildContext context) async {
final picked = await showCupertinoModalPopup<T>(
context: context,
builder: (sheet) => CupertinoActionSheet(
title: Text(label),
actions: [
for (final choice in choices)
CupertinoActionSheetAction(
key: choice.key,
isDefaultAction: choice.checked ?? false,
onPressed: () => Navigator.of(sheet).pop(choice.value),
child: Text(
choice.checked ?? false ? '${choice.label} ✓' : choice.label,
),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.of(sheet).pop(),
child: const Text('Cancel'),
),
),
);
if (picked != null) onSelected(picked);
}
}