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

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


当前回答

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

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

其他回答

更新:Scaffold.of(上下文)。showSnackBar在Flutter 2.0.0中已弃用(稳定)

你可以使用ScaffoldMessenger.of(context)访问父类ScaffoldMessengerState。

然后做一些类似的事情

ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text("Sending Message"),
    ));

零食条是材料设计的官方“吐司”。看到间小吃店。

下面是一个完整的例子:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  const Home({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Snack bar'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () => _showToast(context),
          child: const Text('Show toast'),
        ),
      ),
    );
  }

  void _showToast(BuildContext context) {
    final scaffold = ScaffoldMessenger.of(context);
    scaffold.showSnackBar(
      SnackBar(
        content: const Text('Added to favorite'),
        action: SnackBarAction(label: 'UNDO', onPressed: scaffold.hideCurrentSnackBar),
      ),
    );
  }
}

答案Scaffold.of(context). showsnackbar(…)在大多数情况下都不起作用。

我建议最佳的方法是在类中声明一个Scaffold state键,并将其分配给Scaffold,如下所示:

GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

然后

Scaffold(
  key: _scaffoldKey,
  ...
)

当你想要显示零食栏时,这样做:

_scaffoldKey.currentState.showSnackBar(SnackBar(
  content: Text("This works!"),
));

将flutter_just_toast添加到Pubspecs中的依赖项中。yaml文件。

依赖关系:

flutter_just_toast: ^1.0.1

接下来将包导入到你的类中:

import 'package:flutter_just_toast/flutter_just_toast.dart';

用一条消息实现Toast:

Toast.show(message: "Your toast message",
    duration: Delay.SHORT,
    textColor: Colors.black);

fluttertoast: ^ 3.1.3

import 'package:fluttertoast/fluttertoast.dart';

Fluttertoast.showToast(
        msg: "This is Center Short Toast",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );

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