fluttertoast

repository·master·Indexed 23 days ago

https://github.com/ponnamkarthik/fluttertoast

A Flutter library for displaying toast messages. It offers two modes: a simple, system-style toast via Fluttertoast.showToast() that does not require BuildContext (supported on Android, iOS, and Web), and a highly customizable system via FToast that requires BuildContext to display custom widgets and supports queuing across all platforms.

Tokens
4K
Snippets
8
Records
16
Agent score
31%

What's inside fluttertoast

  1. How toast types differ: No BuildContext vs BuildContext

    master

    The library provides two distinct ways to display toasts:

    1. Toast with no context: Uses Fluttertoast.showToast(). It is simpler but has limited UI control. Supported on Android, iOS, and Web (via Toastify-JS).
    2. Toast with BuildContext: Uses FToast. It provides full UI control (custom widgets), supports queuing, and works on all platforms. It requires initializing FToast with a BuildContext and configuring the MaterialApp builder.
  2. Access FToast context globally using NavigatorKey

    master

    To use FToast outside of a standard widget lifecycle (e.g., globally), use a GlobalKey<NavigatorState> to provide context.

    1. Define the key in main.dart:
    GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
    1. Pass the key to MaterialApp:
    MaterialApp(
        navigatorKey: navigatorKey,
        builder: FToastBuilder(),
        ...
    )
    1. Initialize FToast using the key's context:
    FToast fToast = FToast();
    fToast.init(navigatorKey.currentContext!);
  3. Create custom Android toasts

    master

    To use custom styling on Android, create a layout file named toast_custom.xml in your project's app/res/layout folder. Note that this is a native Android configuration.

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginStart="50dp"
        android:background="@drawable/corner"
        android:layout_marginEnd="50dp">
    
        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#CC000000"
            android:paddingStart="16dp"
            android:paddingTop="10dp"
            android:paddingEnd="16dp"
            android:paddingBottom="10dp"
            android:textStyle="bold"
            android:textColor="#FFFFFF"
            tools:text="Toast should be short." />
    </FrameLayout>
  4. Use Toast with BuildContext (FToast)

    master

    For full control over UI and queuing, use the FToast class. This works on all platforms but requires setup in your MaterialApp and initialization with a BuildContext.

    1. Setup MaterialApp

    Update your MaterialApp to include the FToastBuilder in the builder property:

    MaterialApp(
        builder: FToastBuilder(),
        home: MyApp(),
        navigatorKey: navigatorKey,
    ),

    2. Initialize FToast

    Initialize FToast in your widget's initState:

    FToast fToast;
    
    @override
    void initState() {
        super.initState();
        fToast = FToast();
        fToast.init(context);
    }

    3. Show a Custom Toast

    Pass any widget to fToast.showToast() to display it as a toast.

    _showToast() {
        Widget toast = Container(
            padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
            decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(25.0),
            color: Colors.greenAccent,
            ),
            child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
                Icon(Icons.check),
                SizedBox(
                width: 12.0,
                ),
                Text("This is a Custom Toast"),
            ],
            ),
        );
    
        fToast.showToast(
            child: toast,
            gravity: ToastGravity.BOTTOM,
            toastDuration: Duration(seconds: 2),
        );
    }
  5. How FToast and Fluttertoast differ

    master

    The library provides two distinct ways to show toasts:

    1. Fluttertoast.showToast():

      • Mechanism: Uses native platform APIs (Android/iOS/Web).
      • Context: Does not require BuildContext.
      • Content: Primarily for text messages (msg).
      • Use Case: Quick, simple system-style notifications.
    2. FToast:

      • Mechanism: Uses Flutter's Overlay system (Dart-only).
      • Context: Requires init(context) before use.
      • Content: Can display any arbitrary Flutter Widget.
      • Use Case: Highly customized UI toasts that need to match your app's design.
  6. Manage FToast toasts (Remove and Clear)

    master

    When using FToast, you can manage active and queued toasts using these methods:

    • fToast.removeCustomToast(): Removes the currently showing toast.
    • fToast.removeQueuedCustomToasts(): Clears all toasts currently in the queue.
    // To remove present showing toast
    fToast.removeCustomToast()
    
    // To clear the queue
    fToast.removeQueuedCustomToasts();
  7. Use Toast with no BuildContext (Android & iOS)

    master

    Use Fluttertoast.showToast() for simple, system-style toast messages. This method does not require a BuildContext but offers limited UI customization.

    Supported Platforms: Android, iOS, Web.

    Note for Android: On Android 11 and above, custom styling is limited. Only msg and toastLength will be respected; other properties like backgroundColor or fontSize are ignored.

    import 'package:fluttertoast/fluttertoast.dart';
    
    Fluttertoast.showToast(
            msg: "This is Center Short Toast",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0
        );
  8. Reference: FToast.showToast() parameters

    master

    Parameters for fToast.showToast():

    | property               | description                                                                                        | default                     |
    | ---------------------- | -------------------------------------------------------------------------------------------------- | --------------------------- |
    | child                  | Widget (Not Null)(required)                                                                        | required                    |
    | toastDuration          | Duration (optional)                                                                                |                             |
    | gravity                | ToastGravity.*                                                                                     |
    | positionedToastBuilder | PositionedToastBuilder                                                                             |
    | fadeDuration           | Duration                                                                                           | Duration(milliseconds: 350) |
    | ignorePointer         | boolean                                                                                            | false                       |
    | isDismissible          | boolean                                                                                            | false                       |
  9. Reference: Fluttertoast.showToast() parameters

    master

    Parameters for Fluttertoast.showToast():

    | property           | description                                                                                        | default                                     |
    | ------------------ | -------------------------------------------------------------------------------------------------- | ------------------------------------------- |
    | msg                | String (Not Null)(required)                                                                        | required                                    |
    | toastLength        | Toast.LENGTH_SHORT or Toast.LENGTH_LONG (optional)                                                 | Toast.LENGTH_SHORT                          |
    | gravity            | ToastGravity.TOP (or) ToastGravity.CENTER (or) ToastGravity.BOTTOM (Web Only supports top, bottom) | ToastGravity.BOTTOM                         |
    | timeInSecForIosWeb | int (for ios & web)                                                                                | 1 (sec)                                     |
    | backgroundColor    | Colors.red                                                                                         | null                                        |
    | textcolor          | Colors.white                                                                                       | null                                        |
    | fontSize           | 16.0 (float)                                                                                       | null                                        |
    | fontAsset          | Path to a font file in the Flutter app assets folder, e.g. 'assets/path/to/some-font.ttf' (String) | null                                        |
    | webShowClose       | false (bool)                                                                                       | false                                       |
    | webBgColor         | String (hex Color)                                                                                 | linear-gradient(to right, #00b09b, #96c93d) |
    | webPosition        | String (`left`, `center` or `right`)                                                               | right                                       |