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

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


当前回答

只需使用SnackBar(内容:文本(“hello”),)在任何事件如onTap和onPress。

你可以阅读更多关于展示小吃店的信息。

其他回答

您可以使用飘动吐司包装。为此,将其添加到pubspec中。Yaml文件如下:

dependencies:
  fluttertoast: ^8.0.8

然后在需要吐司的.dart文件中导入这个包并编写代码。

例如,参考以下代码:

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

class ToastExample extends StatefulWidget {
    @override
    _ToastExampleState createState() {
      return _ToastExampleState();
    }
  }

  class _ToastExampleState extends State {
    void showToast() {
      Fluttertoast.showToast(
          msg: 'This is flutterToast example', // Message
          toastLength: Toast.LENGTH_SHORT,    // toast length
          gravity: ToastGravity.CENTER,      // position
          timeInSecForIos: 1,               // duaration
          backgroundColor: Colors.red,     // background color
          textColor: Colors.white         // text color
      );
    }

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Toast Tutorial',
        home: Scaffold(
            appBar: AppBar(
              title: Text('Toast Tutorial'),
            ),
            body: Padding(
              padding: EdgeInsets.all(15.0),
              child: Center(
                child: RaisedButton(
                  child: Text('Show Toast'),
                  onPressed: showToast,
                ),
              ),
            )
        ),
      );
    }
  }

  void main() => runApp(ToastExample());

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();
            },
          )
        ],
      );
    },
  );
});

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

显示Toast的语法:

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

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

 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
          },
        ),
      ),
    );

导入库fluttertoast: 3.1.3

像下面这样使用它:

Fluttertoast.showToast(
    msg: "Hello, World!",
    textColor: Colors.white,
    toastLength: Toast.LENGTH_SHORT,
    timeInSecForIos: 1,
    gravity: ToastGravity.BOTTOM,
    backgroundColor: Colors.indigo,
);