oktoast

repository·main·Indexed 19 days ago

https://github.com/openflutter/flutter_oktoast

A pure Dart toast library for Flutter that enables highly customizable toast notifications. It allows developers to display text or custom widgets as toasts without manually passing BuildContext through the widget tree. Key features include global configuration via the OKToast widget, custom animations, and the ability to manage toast lifecycles using ToastFuture.

Tokens
3.7K
Snippets
10
Records
12
Agent score
68%

What's inside oktoast

  1. Install and Setup oktoast

    main

    To use oktoast in your Flutter project, follow these steps:

    1. Add the dependency to your pubspec.yaml:

      flutter pub add oktoast
    2. Import the library in your Dart files:

      import 'package:oktoast/oktoast.dart';
    3. Wrap your app widget with OKToast. This ensures toasts are displayed in front of all other controls and allows the library to cache context so you can call toast methods anywhere without passing a BuildContext.

    Important: Handling No MediaQuery widget found errors If you encounter this error, wrap the MaterialApp builder instead of wrapping the MaterialApp itself:

    MaterialApp(
      builder: (BuildContext context, Widget? widget) {
        return OKToast(child: widget);
      },
    );
    import 'package:oktoast/oktoast.dart';
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return OKToast(
          child: MaterialApp(
            home: MyHomePage(),
          ),
        );
      }
    }
  2. Configure global `OKToast` properties

    main

    The OKToast widget accepts several parameters to define the default style and behavior for all toasts in your application.

    nametypedesc
    childWidgetRequired. Usually your MaterialApp.
    textStyleTextStyleDefault text style.
    radiusdoubleDefault corner radius.
    backgroundColorColorDefault background color.
    positionToastPositionDefault position.
    dismissOtherOnShowboolIf true, other toasts will be dismissed when a new one shows. Default false.
    movingOnWindowChangeboolIf true, toast moves when window size changes. Default true.
    textDirectionTextDirectionDefault text direction.
    textPaddingEdgeInsetsGeometryOuter margin of text.
    textAlignTextAlignAlignment when text wraps.
    handleTouchboolIf true, toasts can respond to touch events. Default false.
    animationBuilderOKToastAnimationBuilderCustom animation for show/hide.
    animationDurationDurationDuration of animation.
    animationCurveCurveCurve of animation.
    durationDurationDefault duration of the toast.
  3. Show a text toast with `showToast`

    main

    Use the showToast method to display a simple text message.

    Parameters:

    • msg (String, required): The text to display.
    • context (BuildContext, optional): The context for the toast.
    • duration (Duration, optional): How long the toast stays visible.
    • position (ToastPosition, optional): Where to show the toast (e.g., ToastPosition.top, ToastPosition.bottom).
    • textStyle (TextStyle, optional): Style for the toast text.
    • textPadding (EdgeInsetsGeometry, optional): Outer margin of the text.
    • backgroundColor (Color, optional): Background color of the toast.
    • radius (double, optional): Corner radius of the toast.
    • onDismiss (Function, optional): Callback triggered when the toast is dismissed.
    • textDirection (TextDirection, optional): Text direction.
    • dismissOtherToast (bool, optional): If true, dismisses other active toasts.
    • textAlign (TextAlign, optional): Text alignment when wrapping.
    • animationBuilder (OKToastAnimationBuilder, optional): Custom animation.
    • animationDuration (Duration, optional): Duration of the animation.
    • animationCurve (Curve, optional): Curve of the animation.

    Returns a ToastFuture which can be used to manually dismiss the toast.

    showToast(
      "$_counter",
      duration: Duration(seconds: 2),
      position: ToastPosition.bottom,
      backgroundColor: Colors.black.withOpacity(0.8),
      radius: 13.0,
      textStyle: TextStyle(fontSize: 18.0),
    );
  4. Show a custom widget toast with `showToastWidget`

    main

    Use showToastWidget to display any custom Flutter widget as a toast.

    Parameters:

    • widget (Widget, required): The widget you want to display.
    • context (BuildContext, optional): The context for the toast.
    • duration (Duration, optional): How long the toast stays visible.
    • position (ToastPosition, optional): Where to show the toast.
    • onDismiss (Function, optional): Callback triggered when the toast is dismissed.
    • dismissOtherToast (bool, optional): If true, dismisses other active toasts.
    • textDirection (TextDirection, optional): Text direction.
    • handleTouch (bool, optional): If true, the toast can respond to touch events.
    • animationBuilder (OKToastAnimationBuilder, optional): Custom animation.
    • animationDuration (Duration, optional): Duration of the animation.
    • animationCurve (Curve, optional): Curve of the animation.

    Returns a ToastFuture which can be used to manually dismiss the toast.

    ToastFuture toastFuture = showToastWidget(
      Text('hello oktoast'),
      duration: Duration(seconds: 3),
      onDismiss: () {
        print("the toast dismiss");
      },
    );
    
    // To dismiss manually:
    toastFuture.dismiss();
  5. Configure toast appearance with ToastTheme

    main

    The ToastTheme class allows you to customize the visual style and behavior of all toasts in your application. It is implemented as an InheritedWidget, meaning you can provide a custom theme higher up in your widget tree to affect all subsequent showToast calls.

    Key customization properties include:

    • textStyle: The TextStyle for the toast text.
    • backgroundColor: The background color of the toast (defaults to Colors.black).
    • radius: The corner radius of the toast.
    • position: The ToastPosition where the toast appears.
    • duration: How long the toast remains visible.
    • animationBuilder, animationDuration, and animationCurve: Controls the entry/exit animations.
    • dismissOtherOnShow: If true, showing a new toast will dismiss any currently visible toast (defaults to true).
    • textPadding, textAlign, textMaxLines, and textOverflow: Controls the layout and styling of the text content.
    ToastTheme(
      textStyle: TextStyle(color: Colors.white, fontSize: 14),
      textDirection: TextDirection.ltr,
      handleTouch: true,
      radius: 10.0,
      position: ToastPosition.bottom,
      backgroundColor: Colors.blueAccent,
      duration: Duration(seconds: 2),
      child: YourApp(),
    );
  6. Dismiss a toast using ToastFuture

    main

    When you call showToast, it returns a ToastFuture object. You can use this object to manually dismiss the toast before its duration expires.

    Calling dismiss() will remove the toast from the screen. You can optionally pass showAnim: true to trigger the dismissal animation before the toast is removed from the overlay.

    // Assuming showToast returns a ToastFuture
    ToastFuture toast = showToast('Hello World');
    
    // Dismiss immediately without animation
    toast.dismiss();
    
    // OR dismiss with the dismissal animation
    toast.dismiss(showAnim: true);
  7. Configure toast screen position with ToastPosition

    main

    The ToastPosition class defines where a toast appears on the screen using an AlignmentGeometry and a vertical offset.

    You can use the predefined static constants for common positions:

    • ToastPosition.center: Centered on the screen (default).
    • ToastPosition.bottom: Positioned at the bottom center with a default offset of -30.0.
    • ToastPosition.top: Positioned at the top center with a default offset of 75.0.

    To create a custom position or modify an existing one, use the constructor or the copyWith method.

    // Using predefined positions
    final position = ToastPosition.top;
    
    // Creating a custom position
    final customPosition = ToastPosition(align: Alignment.bottomLeft, offset: -50.0);
    
    // Modifying an existing position
    final modifiedPosition = ToastPosition.bottom.copyWith(offset: -10.0);
  8. Configure the OKToast widget

    main

    The OKToast widget is the root component required to enable toast functionality in your application. It should typically wrap your WidgetsApp (or MaterialApp). By configuring OKToast, you define the global default appearance and behavior for all toasts shown via showToast.

    OKToast(
      child: MaterialApp(
        home: MyHomePage(),
      ),
      backgroundColor: Colors.black.withOpacity(0.7),
      radius: 20.0,
      position: ToastPosition.bottom,
      duration: Duration(seconds: 2),
      textStyle: TextStyle(color: Colors.white, fontSize: 14),
    )
  9. Access the current ToastTheme

    main

    To retrieve the current ToastTheme configuration from the widget tree, use the static ToastTheme.of(BuildContext context) method. This is useful if you need to inspect the current theme settings or if you are building custom components that depend on the toast's visual state.

    ToastTheme currentTheme = ToastTheme.of(context);
  10. OKToast configuration properties

    main

    The OKToast widget accepts several properties to customize the global toast theme. These settings are passed down to the ToastTheme and apply to all subsequent toast calls.

    ```dart
    const OKToast({
      super.key,
      required this.child,
      this.textStyle,
      this.radius = 10.0,
      this.position = ToastPosition.center,
      this.textDirection = TextDirection.ltr,
      this.dismissOtherOnShow = false,
      this.movingOnWindowChange = true,
      Color? backgroundColor,
      this.textPadding,
      this.textAlign,
      this.handleTouch = false,
      this.animationBuilder,
      this.animationDuration = _defaultAnimDuration,
      this.animationCurve,
      this.duration,
    });
    PropertyTypeDescription
    childWidgetThe application widget tree (e.g., MaterialApp).
    textStyleTextStyle?Default text style for all toasts.
    backgroundColorColorDefault background color for the toast bubble.
    radiusdoubleDefault corner radius of the toast bubble.
    positionToastPositionDefault screen position (e.g., ToastPosition.center).
    textDirectionTextDirectionDefault text direction (ltr or rtl).
    dismissOtherOnShowboolIf true, showing a new toast will dismiss the current one.
    movingOnWindowChangeboolIf true, the toast will reposition when the window size changes (e.g., keyboard appearing).
    textPaddingEdgeInsets?Default padding inside the toast bubble.
    textAlignTextAlign?Default text alignment.
    handleTouchboolIf true, toasts can respond to click events.
    animationBuilderOKToastAnimationBuilder?Custom builder for show/hide animations.
    animationDurationDurationDuration of the entrance/exit animations.
    animationCurveCurve?The curve used for animations.
    durationDuration?How long the toast remains visible on screen.
  11. Check the status of a toast with ToastFuture

    main

    The ToastFuture class provides two properties to track the lifecycle of a toast:

    • mounted: Returns true if the toast is currently being displayed on the screen.
    • dismissed: Returns true if the toast has been dismissed (either manually via dismiss() or automatically).
    if (toast.mounted) {
      print('Toast is currently visible');
    }
    
    if (toast.dismissed) {
      print('Toast is no longer active');
    }