我可以在Flutter中创建类似Toasts的东西吗?

只是一个很小的通知窗口,不直接面对用户,也不锁定或淡出它后面的视图。


当前回答

你可以很容易地实现这种效果使用叠加。

代码:

OverlayEntry entry = OverlayEntry(builder: (context) {
              return Positioned(
                  top: MediaQuery.of(context).size.height * 0.8,
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    alignment: Alignment.center,
                    child: const Card(
                      color: Colors.redAccent,
                      child: Padding(
                        padding: EdgeInsets.all(8),
                        child: Text("This is a message."),
                      ),
                    ),
                  ));
            });

            //show overlay
            Overlay.of(context)!.insert(entry);
            //auto remove this overlay after 3 seconds
            Future.delayed(const Duration(seconds: 3)).then((value) => entry.remove());

截图:

其他回答

Importcupertino_icons: ^0.1.2并编写以下代码:

showToast(BuildContext context, String message) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return CupertinoAlertDialog(
        title: Text(
          "Name of App",
        ),
        content: Text(
          message,
        ),
        actions: [
          CupertinoButton(
            child: Text("OK"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          )
        ],
      );
    },
  );
});

在Flutter中显示Toast消息非常简单:

Scaffold.of(context).showSnackBar(SnackBar(
    content: Text("Toast Text Here"),
));

这很简单:

我们只需要安装颤动吐司包。 请参考以下文档: https://pub.dev/packages/fluttertoast

在安装选项卡,你会得到依赖,你必须把它粘贴到pubspec。Yaml文件然后安装。

在此之后,只需导入包:

import 'package:fluttertoast/fluttertoast.dart';

类似于上面的一行。

然后通过使用FlutterToast类你可以使用你的FlutterToast。

你做完了! !

你可以直接使用小吃店的元素

 ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text("Successfully!"),
        behavior: SnackBarBehavior.floating,
        margin: EdgeInsets.all(20),
          shape: StadiumBorder(),
        action: SnackBarAction(
          label: 'Dismiss',
          disabledTextColor: Colors.white,
          textColor: Colors.blue,
          onPressed: () {
            //Do whatever you want
          },
        ),
      ),
    );

用https://pub.dev/packages/toast做吐司。这个库非常容易使用,适用于iOS和Android。

显示Toast的语法:

Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity:  Toast.BOTTOM);