乐闻世界logo
搜索文章和话题

How to create Toast in Flutter

1个答案

1

Creating toast notifications in Flutter can be achieved in two primary approaches: utilizing third-party packages such as fluttertoast or customizing a Widget to implement toast functionality. I will explain both methods in detail.

Method 1: Using the Third-Party Package fluttertoast

  1. Add Dependency: First, add the fluttertoast package dependency to your project's pubspec.yaml file.

    yaml
    dependencies: flutter: sdk: flutter fluttertoast: ^8.0.8

    Then run flutter pub get to install the package.

  2. Using fluttertoast: Import the package and use it to display toast notifications where needed.

    dart
    import 'package:fluttertoast/fluttertoast.dart'; void showToast() { Fluttertoast.showToast( msg: "This is a toast message", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER, timeInSecForIosWeb: 1, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0 ); }

    In this example, the showToast function can be called wherever you need to display a toast notification.

Method 2: Custom Toast Widget

  1. Create a Toast Widget: You can create a custom Widget to simulate toast functionality.

    dart
    import 'package:flutter/material.dart'; class CustomToast extends StatelessWidget { final String message; final Color backgroundColor; final Color textColor; const CustomToast({ Key? key, required this.message, this.backgroundColor = Colors.black54, this.textColor = Colors.white, }) : super(key: key); Widget build(BuildContext context) { return Align( alignment: Alignment.center, child: Container( padding: EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(25.0), color: backgroundColor, ), child: Text(message, style: TextStyle(color: textColor)), ), ); } }
  2. Display Custom Toast: You can use the Overlay API to display the custom Toast Widget on the screen.

    dart
    void showCustomToast(BuildContext context, String message) { var overlayEntry = OverlayEntry( builder: (context) => CustomToast(message: message), ); Overlay.of(context)!.insert(overlayEntry); Future.delayed(Duration(seconds: 2), () => overlayEntry.remove()); }

    In this example, the showCustomToast function can be called wherever you need to display a toast notification.

Summary

Utilizing the third-party package fluttertoast enables a quick and straightforward implementation of toast notifications in Flutter applications, whereas a custom Toast Widget offers greater flexibility. Select the method that best suits your specific requirements.

2024年7月1日 12:48 回复

你的答案