Toast, Simplified: Customizing Notifications with 'fluttertoast' Library

Published on by Flutter News Hub

Toast, Simplified: Customizing Notifications with 'fluttertoast' Library

Enhance your Flutter applications with 'fluttertoast', a versatile library that simplifies the display of customizable toast messages. With its two distinct modes, you can effortlessly create notifications that cater to your specific requirements.

Toasts Without BuildContext (Android and iOS)

This simplified mode offers limited UI control but provides essential features:

Fluttertoast.showToast(
  msg: "This is Center Short Toast",
  toastLength: Toast.LENGTH_SHORT,
  gravity: ToastGravity.CENTER,
  timeInSecForIosWeb: 1,
);

Toasts with BuildContext (All Platforms)

For ultimate customization and control, utilize the FToast widget:

import 'package:fluttertoast/fluttertoast.dart';

...

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

_showToast() {
  Widget toast = Container(
    // Custom styling...
  );

  fToast.showToast(
    child: toast,
    gravity: ToastGravity.BOTTOM,
    toastDuration: Duration(seconds: 2),
  );
}

Customizing Toast Appearance (Android Only)

For custom toast appearances on Android, create a toast_custom.xml file in app/res/layout:

<?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>

Advanced Features

  • Positioning: Specify custom toast positions using positionedToastBuilder.
  • Queue Management: Control the display order and removal of toasts.
  • Global Context Access: Use navigatorKey to access context from anywhere in your app.

Conclusion

'fluttertoast' empowers you to effortlessly enhance user interactions with customizable toast messages. Whether you prefer limited control or full UI customization, this versatile library has you covered. Embrace its simplicity and elevate your Flutter applications today.

Flutter News Hub