Toastification

repository·main·Indexed 21 days ago

https://github.com/payam-zahedi/toastification

A Flutter package for displaying highly customizable, queued toast notifications. It supports predefined styles, custom widget builders, and can be used with or without BuildContext via ToastificationWrapper or GlobalNavigatorKey. Features include custom animations, global configuration through ToastificationConfigProvider, and comprehensive lifecycle callbacks.

Tokens
8.4K
Snippets
28
Records
33
Agent score
73%

What's inside toastification

  1. How to use Toastification without BuildContext

    main

    To display toast messages without providing a context (e.g., from a service or logic class), wrap your root AppWidget with the ToastificationWrapper. This enables the use of toastification.show and toastification.showCustom globally within the app.

    return ToastificationWrapper(
      child: MaterialApp(),
    );
  2. Configure global toast behavior with ToastificationConfigProvider

    main

    Use ToastificationConfigProvider to set default behaviors for all toasts within a specific part of your widget tree. This is achieved by passing a ToastificationConfig instance to the provider.

    Apply to the entire application

    Wrap your MaterialApp using the builder parameter to ensure the configuration is available globally.

    MaterialApp(
      builder: (context, child) {
        return ToastificationConfigProvider(
          config: const ToastificationConfig(
            margin: EdgeInsets.fromLTRB(0, 16, 0, 110),
            alignment: Alignment.center,
            itemWidth: 440,
            animationDuration: Duration(milliseconds: 500),
            blockBackgroundInteraction: false,
          ),
          child: child!,
        );
      },
    );

    Apply to a specific page

    Wrap the specific page's widget tree with ToastificationConfigProvider to override global settings for that route only.

    class HomePage extends StatelessWidget {
      const HomePage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const ToastificationConfigProvider(
          config: ToastificationConfig(
            margin: EdgeInsets.fromLTRB(0, 16, 0, 110),
            alignment: Alignment.center,
            itemWidth: 440,
            animationDuration: Duration(milliseconds: 500),
            blockBackgroundInteraction: false,
          ),
          child: Scaffold(
            body: HomeBody(),
          ),
        );
      }
    }
  3. Show toasts using GlobalNavigatorKey

    main

    If you cannot access BuildContext (e.g., in GetX or deep logic layers), you can use a GlobalKey<NavigatorState> to show toasts via the overlayState.

    1. Create a key: final GlobalKey<NavigatorState> globalNavigatorKey = GlobalKey<NavigatorState>();
    2. Assign it to your MaterialApp: MaterialApp(navigatorKey: globalNavigatorKey, ...)
    3. Use the key to access the overlay:

    For show():

    toastification.show(
      overlayState: globalNavigatorKey.currentState?.overlay,
      title: Text('Hello, World!'),
    );

    For showCustom():

    toastification.showCustom(
      overlayState: globalNavigatorKey.currentState?.overlay,
      builder: (context, holder) {
         return YourCustomWidget();
      },
    );
    toastification.show(
      overlayState: navigatorKey.currentState?.overlay,
      autoCloseDuration: const Duration(seconds: 5),
      title: Text('Hello, World!'),
    );
  4. Customize iOS Launch Screen Assets

    main

    To change the image used for the iOS launch screen, you can either replace the image files directly in the example/ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory or use Xcode for a more visual approach.

    Using Xcode:

    1. Open your Flutter project's iOS workspace using the command: open ios/Runner.xcworkspace.
    2. In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
    3. Drag and drop your desired images into the asset catalog to replace the existing launch images.
    open ios/Runner.xcworkspace
  5. How Toastification manages notifications

    main

    Toastification uses internal ToastificationManager instances to handle the lifecycle of notifications for specific Alignment positions.

    Key behaviors include:

    • Automatic Queueing: When a new toast is shown, it is inserted at the top of the list. If the number of active notifications exceeds the maxToastLimit defined in your ToastificationConfig, the oldest toast is automatically dismissed.
    • Overlay Lifecycle: An OverlayEntry is created when the first notification is shown and is automatically removed and disposed of once the last notification has finished its dismissal animation.
    • Dismissal Logic: Notifications can be dismissed individually, all at once, or by targeting the first/last item. Dismissal can include a removal animation or be instantaneous.
    • Interaction Blocking: Depending on your ToastificationConfig, the manager can wrap the overlay in a GestureDetector to block background interactions when blockBackgroundInteraction is enabled.
  6. Understand the ToastificationItem model

    main

    A ToastificationItem represents an individual toast notification instance. It contains the configuration for how the toast is built, where it is aligned, and how it animates.

    Important: Do not instantiate ToastificationItem directly. Instead, use the Toastification class (via show or showCustom methods) to create instances. The returned ToastificationItem can be used to manually control the toast's lifecycle (starting, pausing, or stopping the auto-close timer) or to identify specific toasts via their unique id.

  7. Configure blockBackgroundInteraction

    main

    The blockBackgroundInteraction property in ToastificationConfig controls whether the user can interact with the background UI while a toast is visible.

    • When true: The background is blocked from receiving touch events.
    • When false (default): The background remains interactive.
    ToastificationConfig(
      blockBackgroundInteraction: true, // Blocks background interaction
      // ... other configuration options
    )
  8. Initialize Toastification with ToastificationWrapper

    main

    To use Toastification (especially to enable the show method without a BuildContext), you must wrap your application's root widget with the ToastificationWrapper. This widget initializes the global overlay and provides configuration to all descendant widgets.

    If you do not wrap your app with ToastificationWrapper, calling toast methods will result in a FlutterError stating that Toastification is not initialized.

    ToastificationWrapper(
      config: ToastificationConfig(
        // your global configuration here
      ),
      child: MaterialApp(
        title: 'My Application',
        home: HomePage(),
      ),
    );
  9. Customize toast animations

    main

    You can implement custom entry/exit animations for toast notifications by providing an animationBuilder function and specifying an animationDuration. The animationBuilder provides the context, an animation object (typically an Animation<double>), the alignment, and the child (the toast widget itself).

    ttoastification.show(
      context: context,
      title: Text('Hello, world!'),
      // .... Other parameters
      animationDuration: const Duration(milliseconds: 300),
      animationBuilder: (context, animation, alignment, child) {
        return RotationTransition(
          turns: animation,
          child: child,
        );
      },
    );