promptMultiSelect function
Several choices; returns the checked ones in list order, or null if
cancelled. Empty choices returns an empty list.
Space (or x) toggles, a toggles all, Enter confirms. The
indexes in initial start checked.
In plain mode it writes title and the numbered choices, then reads
comma-separated numbers; empty input keeps initial.
Implementation
Future<List<String>?> promptMultiSelect(
List<String> choices, {
List<ProgramOption> options = const [],
String title = 'Choose any',
Set<int> initial = const {},
}) async {
if (choices.isEmpty) return const [];
List<String> pick(Iterable<int> picks) =>
[for (final i in picks.toList()..sort()) choices[i]];
final program = Program(options: options);
final plain = PlainSession.open(program);
if (plain != null) {
return plain.run((io) async {
final picks = await io.askMany([title], choices,
defaults: {
for (final i in initial)
if (i >= 0 && i < choices.length) i
});
if (picks != null) _reportSelection(picks.toList()..sort());
return picks == null ? null : pick(picks);
});
}
final model = _MultiPromptModel(
MultiSelectModel(
title: title,
items: [
for (final (i, c) in choices.indexed)
MultiSelectItem(label: c, selected: initial.contains(i)),
],
),
summary: _summary,
);
final picks = await program.runForResult(model);
if (picks != null) _reportSelection(picks);
return picks == null ? null : pick(picks);
}