Flutter - 如何获取当前上下文? [英] Flutter - how to get current context?

查看:37
本文介绍了Flutter - 如何获取当前上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Firebase 云消息传递通知,当我在应用程序内收到通知时,我想显示一个对话框或快餐栏,我的问题是我正在我的小部件树顶部初始化 firebase 配置(应用程序启动后启动画面)

I am using Firebase cloud messaging for notifications, and i want to show a dialog or snackbar once i receive a notification when i am inside the application, my problem is that i am initializing the firebase configuration at the top of my widget tree (Splash screen once the app is starting)

_fireBaseMessaging.configure(
  onMessage: (Map<String, dynamic> message) async {
    dynamic data = message['data'];
    ................ // Adding a snackbar/alertdialog here doesn't work
  },
);

显然,如果我设置了一个对话框或小吃栏,因为我需要当前页面的上下文,所以它不会显示,有没有办法获取当前上下文?

obviously if i set a dialog or snackbar it won't show since i need the context of my current page, is there any way to get the current context?

我也尝试将它放在启动屏幕的构建小部件中,但是一旦我在另一个页面上,对话框仍然没有显示.

I also tried putting it inside the build widget of my splash screen but still the dialog isn't showing once i am on another page.

 @override
  Widget build(BuildContext context) {
    _fireBaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        dynamic data = message['data'];
        if (data['id'] == '1') {
          newPro = true;
        } else if (data['id'] == '2') {
          print("THIS WORKS!!!");
          showDialog(
              context: context,
              builder: (context) => AlertDialog(
                    content: ListTile(
                      title: Text("TEST"),
                      subtitle: Text("TEST"),
                    ),
                    actions: <Widget>[
                      FlatButton(
                        child: Text("OK"),
                        onPressed: () => Navigator.pop(context),
                      )
                    ],
                  ));
        }
      },
    );

推荐答案

我最终使用了 Overlay 支持:

I ended up using Overlay support:

https://pub.dev/packages/overlay_support

它基本上是在我的树的最开始被调用的,就像在 main.dart 中包装提供者一样,它就像一个魅力,没有其他任何作用!这里还有一个对我帮助很大的教程:

It is basically called at the very beginning of my tree just like wrapping providers at the main.dart, it worked like a charm, nothing else worked at all! Also here is a tutorial that helped me a lot:

https://medium.com/flutter-community/in-app-notifications-in-flutter-9c1e92ea10b3

这篇关于Flutter - 如何获取当前上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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