lemmur-app-android/lib/widgets/radio_picker.dart

81 lines
2.1 KiB
Dart
Raw Normal View History

2021-02-09 15:12:13 +01:00
import 'package:flutter/material.dart';
import 'bottom_modal.dart';
/// A picker with radio values (only one value can be picked at once)
class RadioPicker<T> extends StatelessWidget {
final List<T> values;
final T groupValue;
final ValueChanged<T>? onChanged;
2021-02-09 15:12:13 +01:00
/// Map a given value to a string for display
final String Function(T)? mapValueToString;
final String? title;
2021-02-09 15:12:13 +01:00
/// custom button builder. When null, an OutlinedButton is used
final Widget Function(
2021-04-17 23:59:33 +02:00
BuildContext context, String displayValue, VoidCallback? onPressed)?
2021-02-09 15:12:13 +01:00
buttonBuilder;
final Widget? trailing;
2021-02-09 15:12:13 +01:00
const RadioPicker({
2022-05-11 22:23:18 +02:00
super.key,
required this.values,
required this.groupValue,
required this.onChanged,
2021-02-09 15:12:13 +01:00
this.mapValueToString,
this.buttonBuilder,
this.title,
this.trailing,
2022-05-11 22:23:18 +02:00
});
2021-02-09 15:12:13 +01:00
@override
Widget build(BuildContext context) {
final mapValueToString =
this.mapValueToString ?? (value) => value.toString();
final buttonBuilder = this.buttonBuilder ??
(context, displayString, onPressed) => OutlinedButton(
onPressed: onPressed,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(displayString),
const Icon(Icons.arrow_drop_down),
],
),
);
Future<void> onPressed() async {
final value = await showBottomModal<T>(
context: context,
title: title,
builder: (context) => Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final value in values)
RadioListTile<T>(
value: value,
groupValue: groupValue,
title: Text(mapValueToString(value)),
onChanged: (value) => Navigator.of(context).pop(value),
),
if (trailing != null) trailing!
2021-02-09 15:12:13 +01:00
],
),
);
if (value != null) {
onChanged?.call(value);
}
}
2021-04-17 23:59:33 +02:00
return buttonBuilder(
context,
mapValueToString(groupValue),
onChanged == null ? null : onPressed,
);
2021-02-09 15:12:13 +01:00
}
}