flutter如何实现toast消息提示

在Flutter中如何实现Toast消息提示功能?我试过一些第三方库但效果不太理想,希望了解原生实现方式或推荐稳定可靠的插件。具体需求是:1. 支持自定义显示时长 2. 能调整Toast位置 3. 兼容最新Flutter版本。请问官方是否有推荐方案?最好能提供简单示例代码。

2 回复

Flutter中实现Toast消息提示,可使用第三方库如fluttertoast。安装后在代码中导入,调用Fluttertoast.showToast()方法即可显示消息,支持设置位置、时长等参数。

更多关于flutter如何实现toast消息提示的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现Toast消息提示,主要有以下几种方式:

1. 使用fluttertoast库(推荐)

这是最常用的Toast实现方式:

安装依赖:

dependencies:
  fluttertoast: ^8.2.2

基本使用:

import 'package:fluttertoast/fluttertoast.dart';

// 显示Toast
Fluttertoast.showToast(
    msg: "这是一个Toast消息",
    toastLength: Toast.LENGTH_SHORT,
    gravity: ToastGravity.BOTTOM,
    timeInSecForIosWeb: 1,
    backgroundColor: Colors.black54,
    textColor: Colors.white,
    fontSize: 16.0
);

参数说明:

  • msg: 要显示的消息内容
  • toastLength: 显示时长(SHORT/LONG)
  • gravity: 显示位置(TOP/CENTER/BOTTOM)
  • backgroundColor: 背景颜色
  • textColor: 文字颜色

2. 使用SnackBar(Material Design风格)

// 在BuildContext可用的地方
ScaffoldMessenger.of(context).showSnackBar(
  SnackBar(
    content: Text('这是一个SnackBar消息'),
    duration: Duration(seconds: 2),
    action: SnackBarAction(
      label: '撤销',
      onPressed: () {
        // 执行撤销操作
      },
    ),
  ),
);

3. 自定义Toast组件

如果需要完全自定义样式:

void showCustomToast(BuildContext context, String message) {
  final overlay = Overlay.of(context);
  final overlayEntry = OverlayEntry(
    builder: (context) => Positioned(
      bottom: 100,
      left: MediaQuery.of(context).size.width * 0.1,
      child: Material(
        color: Colors.transparent,
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
          decoration: BoxDecoration(
            color: Colors.black87,
            borderRadius: BorderRadius.circular(25),
          ),
          child: Text(
            message,
            style: TextStyle(color: Colors.white),
          ),
        ),
      ),
    ),
  );
  
  overlay.insert(overlayEntry);
  Future.delayed(Duration(seconds: 2), () {
    overlayEntry.remove();
  });
}

推荐使用fluttertoast库,它兼容性好,支持Android、iOS和Web平台,使用简单且功能完善。

回到顶部