Flutter自定义Toast提示插件custmytoast的使用

Flutter自定义Toast提示插件custmytoast的使用

custmytoast https://pub.dev/packages/custmytoast

Toast库用于Flutter。

Build Checks

现在此Toast库支持两种类型的Toast消息,一种需要BuildContext,另一种不需要BuildContext


无需上下文的Toast(仅限Android与iOS)

支持平台

这一个Toast类型功能有限,无法控制UI。

使用示例

custmytoast.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
    );
属性 描述 默认值
msg 字符串(必填) 必填
toastLength Toast.LENGTH_SHORTToast.LENGTH_LONG(可选) Toast.LENGTH_SHORT
gravity ToastGravity.TOPToastGravity.CENTERToastGravity.BOTTOM(Web仅支持topbottom ToastGravity.BOTTOM
timeInSecForIosWeb iOS 和 Web 的显示时间(秒) 1
backgroundColor 背景颜色 null
textColor 文本颜色 null
fontSize 字体大小(浮点数) 16.0
webShowClose 是否显示关闭按钮(布尔值) false
webBgColor Web背景颜色(十六进制颜色字符串) linear-gradient(to right, #00b09b, #96c93d)
webPosition Web位置(leftcenterright right

取消所有Toast

custmytoast.cancel()

注意事项(Android)

Toast deprecated setView

注意:在Android 11及以上版本中,自定义Toast将不起作用,只会使用msgtoastLength属性,其余属性均被忽略。

自定义Toast样式(Android)

在项目app/res/layout目录下创建名为toast_custom.xml的文件,并进行自定义样式:

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

需要上下文的Toast(支持所有平台)

支持平台

  • 所有平台

特性

  1. 完全控制Toast。
  2. Toast消息会排队。
  3. 可以移除某个Toast。
  4. 清空Toast队列。

使用示例

  1. pubspec.yaml中添加依赖:
dependencies:
  custmytoast: ^0.0.1
  1. 导入库:
import 'package:custmytoast/custmytoast.dart';
  1. 初始化并展示Toast:
FToast fToast;

[@override](/user/override)
void initState() {
    super.initState();
    fToast = FToast();
    fToast.init(context); // 初始化时传入BuildContext
}

_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"),
        ],
        ),
    );

    // 默认Toast
    fToast.showToast(
        child: toast,
        gravity: ToastGravity.BOTTOM,
        toastDuration: Duration(seconds: 2),
    );

    // 自定义Toast位置
    fToast.showToast(
        child: toast,
        toastDuration: Duration(seconds: 2),
        positionedToastBuilder: (context, child) {
          return Positioned(
            child: child,
            top: 16.0,
            left: 16.0,
          );
        });
}

取消所有Toast

// 移除当前显示的Toast
fToast.removeCustomToast();

// 清空队列中的Toast
fToast.removeQueuedCustomToasts();
属性 描述 默认值
child Widget(必填) 必填
toastDuration 显示时长(可选) 无默认值
gravity ToastGravity.TOPToastGravity.BOTTOM 无默认值

示例效果

无需上下文的Toast

No Build Context Toast No Build Context Toast No Build Context Toast No Build Context Toast

需要上下文的Toast

Build Context Toast


示例代码

main.dart

import 'package:custmytoast_example/toast_context.dart';
import 'package:custmytoast_example/toast_no_context.dart';
import 'package:flutter/material.dart';

GlobalKey globalKey = GlobalKey();

void main() => runApp(
      MaterialApp(
        home: MyApp(),
      ),
    );

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      key: globalKey,
      appBar: AppBar(
        title: Text("Toast"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).push(MaterialPageRoute(
                builder: (context) => ToastNoContext(),
              ));
            },
            child: Text("Flutter Toast No Context"),
          ),
          SizedBox(
            height: 24.0,
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).push(MaterialPageRoute(
                builder: (context) => ToastContext(),
              ));
            },
            child: Text("Flutter Toast Context"),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter自定义Toast提示插件custmytoast的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自定义Toast提示插件custmytoast的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,自定义Toast提示插件可以帮助你创建符合应用风格的Toast消息。虽然Flutter本身没有内置的Toast组件,但你可以使用第三方插件或自己实现一个自定义的Toast组件。下面是一个简单的自定义Toast插件的实现和使用方法。

1. 创建自定义Toast插件

首先,创建一个名为 custmytoast 的插件。

custmytoast.dart

import 'package:flutter/material.dart';

class CustMyToast {
  static void showToast(BuildContext context, String message, {Duration? duration}) {
    final overlay = Overlay.of(context);
    final overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
        bottom: 50.0,
        left: MediaQuery.of(context).size.width * 0.1,
        right: MediaQuery.of(context).size.width * 0.1,
        child: Material(
          color: Colors.transparent,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.8),
              borderRadius: BorderRadius.circular(8.0),
            ),
            child: Text(
              message,
              textAlign: TextAlign.center,
              style: const TextStyle(color: Colors.white, fontSize: 16.0),
            ),
          ),
        ),
      ),
    );

    overlay.insert(overlayEntry);

    Future.delayed(duration ?? const Duration(seconds: 2), () {
      overlayEntry.remove();
    });
  }
}

2. 使用自定义Toast插件

在你的Flutter应用中使用 CustMyToast 来显示Toast消息。

main.dart

import 'package:flutter/material.dart';
import 'custmytoast.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Custom Toast Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Toast Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            CustMyToast.showToast(context, 'This is a custom toast message!');
          },
          child: Text('Show Toast'),
        ),
      ),
    );
  }
}
回到顶部