show static method

void show(
  1. String text,
  2. BuildContext context, {
  3. Duration? duration,
  4. Color? background,
  5. TextStyle textStyle = const TextStyle(fontSize: 16, color: Colors.white),
  6. double? radius,
  7. Image? preIcon,
  8. double? verticalOffset,
  9. VoidCallback? onDismiss,
  10. ToastGravity? gravity,
})

显示Toast,如不设置duration则会自动根据内容长度来计算(更友好,最长5秒)

Implementation

static void show(
  String text,
  BuildContext context, {
  Duration? duration,
  Color? background,
  TextStyle textStyle = const TextStyle(fontSize: 16, color: Colors.white),
  double? radius,
  Image? preIcon,
  double? verticalOffset,
  VoidCallback? onDismiss,
  ToastGravity? gravity,
}) {
  final OverlayState? overlayState = Overlay.of(context);
  if (overlayState == null) return;

  preToastView?._dismiss();
  preToastView = null;

  final double finalVerticalOffset = getVerticalOffset(
    context: context,
    gravity: gravity,
    verticalOffset: verticalOffset,
  );

  /// 自动根据内容长度决定显示时长,更加人性化
  final int autoDuration = min(text.length * 0.06 + 0.8, 5.0).ceil();
  final Duration finalDuration = duration ?? Duration(seconds: autoDuration);
  final OverlayEntry overlayEntry = OverlayEntry(
    builder: (context) {
      return _ToastWidget(
        widget: ToastChild(
          background: background,
          radius: radius,
          msg: text,
          leading: preIcon,
          textStyle: textStyle,
          gravity: gravity,
          verticalOffset: finalVerticalOffset,
        ),
      );
    },
  );
  final _ToastView toastView =
      _ToastView(overlayState: overlayState, overlayEntry: overlayEntry);
  preToastView = toastView;
  toastView._show(
    duration: finalDuration,
    onDismiss: onDismiss,
  );
}