showColorPickerDialog function

Future<ColorDerivative> showColorPickerDialog({
  1. required BuildContext context,
  2. required ColorDerivative color,
  3. ValueChanged<ColorDerivative>? onColorChanged,
  4. Widget? title,
  5. ColorPickerMode initialMode = ColorPickerMode.rgb,
  6. bool showAlpha = true,
  7. bool allowPickFromScreen = true,
  8. ColorHistoryStorage? historyStorage,
})

Implementation

Future<ColorDerivative> showColorPickerDialog({
  required BuildContext context,
  required ColorDerivative color,
  ValueChanged<ColorDerivative>? onColorChanged,
  Widget? title,
  ColorPickerMode initialMode = ColorPickerMode.rgb,
  bool showAlpha = true,
  bool allowPickFromScreen = true,
  ColorHistoryStorage? historyStorage,
}) async {
  final GlobalKey<_ColorPickerDialogState> key = GlobalKey();
  while (true) {
    if (!context.mounted) {
      return color;
    }
    final result = await showDialog<_ColorPickerDialogResult>(
      context: context,
      builder: (context) {
        return _ColorPickerDialog(
          key: key,
          color: color,
          onColorChanged: (color) {
            onColorChanged?.call(color);
            if (historyStorage != null) {
              historyStorage.addHistory(color.toColor());
            }
          },
          showAlpha: showAlpha,
          initialMode: initialMode,
          allowPickFromScreen: allowPickFromScreen,
          title: title,
        );
      },
    );
    if (result == null) {
      return color;
    }
    if (result.pickedFromScreen) {
      if (key.currentState != null) {
        final modalRoute = ModalRoute.of(key.currentContext!);
        if (modalRoute != null) {
          await modalRoute.completed;
        }
      }
      if (!context.mounted) {
        return color;
      }
      final picked = await pickColorFromScreen(context);
      if (picked != null) {
        color = color.changeToColor(picked);
      }
      continue;
    }
    if (result.color != null) {
      return result.color!;
    }
    return color;
  }
}