如何在EventChannel.listen的回调onEvent中显示SnackBar [英] How to show a SnackBar in callback onEvent of EventChannel.listen

查看:81
本文介绍了如何在EventChannel.listen的回调onEvent中显示SnackBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 EventChannel 从本机代码接收到一个事件.

An event is received from native code using EventChannel.

内容是字符串,我想用 SnackBar 展示它.

Content is String, and I'd like to show it with SnackBar.

但是 Scaffold.of 返回null.而且我什么也没发现得到 Widget Build(...)创建的 Scaffold BuildContext .

But Scaffold.of returns null. And I found nothing to get BuildContext of Scaffold created by Widget Build(...).

代码如下:

@override
void initState() {
super.initState();

showMsg.receiveBroadcastStream().listen(
    (event) => setState(() {
        Scaffold.of(context).showSnackBar(new SnackBar(
            content: new Text(event.toString()),
        ));
    }),
    onError: (event) => {}
);

推荐答案

编辑/更新的答案

使用新的Flutter更新,您现在必须使用 ScaffoldMessenger 来显示 SnackBar .

With the new Flutter update you now have to use ScaffoldMessenger to show the SnackBar.

ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('test'),
        ),
      );

我正在使用以下Flutter版本和频道

I am using below Flutter version and channel

1.24.0-10.1.pre•频道开发人员•

1.24.0-10.1.pre • channel dev •

旧答案

您将需要一个用于脚手架的钥匙,通过它您可以获取脚手架的状态

You will need a key for the Scaffold using which you can get the state of the Scaffold

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

现在在您的 build 方法中,它必须返回支架.在 Scaffold 中指定键:_scaffoldKey,

Now in your build method, it must return the scaffold. in the Scaffold assign the key: _scaffoldKey,

return new Scaffold(
      key: _scaffoldKey,
      ...,
);

使用此,您可以访问 Scaffold 的状态.

using this key you can access the state of the Scaffold.

_scaffoldKey.currentState.showSnackBar(new SnackBar(
            content: new Text(event.toString()),
));

这篇关于如何在EventChannel.listen的回调onEvent中显示SnackBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆