showSnackBarAlert function

ScaffoldFeatureController<Widget, dynamic> showSnackBarAlert(
  1. BuildContext context, {
  2. String? title,
  3. String? message,
  4. Color? backgroundColor,
  5. SnackbarAlertType? type,
  6. Duration? duration = const Duration(seconds: 3),
})

Implementation

ScaffoldFeatureController showSnackBarAlert(
  BuildContext context, {
  String? title,
  String? message,
  Color? backgroundColor,
  SnackbarAlertType? type,
  Duration? duration = const Duration(seconds: 3),
}) {
  assert(backgroundColor == null || type == null, "You can just set either backgroundColor or type at a time");
  Color? finalBackgroundColor;
  Color? textColor;

  if (backgroundColor != null) {
    finalBackgroundColor = backgroundColor;
  } else if (type == SnackbarAlertType.failure) {
    final Color failureColor = GBTheme.of(context).colorScheme.error;
    finalBackgroundColor = failureColor;
  } else if (type == SnackbarAlertType.success) {
    final Color successColor = Colors.greenAccent;
    finalBackgroundColor = successColor;
  }

  if (finalBackgroundColor != null) {
    final lumen = finalBackgroundColor.computeLuminance();
    textColor = lumen < .5 ? GBTheme.of(context).textWhite : GBTheme.of(context).textBlack;
  } else {
    textColor = GBTheme.of(context).textBlack;
  }

  ScaffoldFeatureController? controller;

  bool closed = false;

  controller = ScaffoldMessenger.of(context).showMaterialBanner(
    MaterialBanner(
      padding: EdgeInsets.only(top: 16, left: 16, bottom: 8),
      backgroundColor: finalBackgroundColor,
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            message ?? "",
            style: GBTheme.of(context).textTheme.bodyLarge?.copyWith(
                  color: textColor,
                ),
          ),
        ],
      ),
      actions: [
        TextButton(
          child: Text(
            "Ok",
            style: TextStyle(
              color: textColor,
            ),
          ),
          onPressed: () {
            // controller = ScaffoldMessenger.of(context).hideCurrentSnackBar();
            controller?.close();
          },
        ),
      ],
      forceActionsBelow: false,
    ),
  );

  controller.closed.then((value) {
    closed = true;
  });

  if (duration != null) {
    Future.delayed(duration).then((value) {
      if (!closed) {
        controller?.close();
      }
    });
  }
  return controller;
}