【问题标题】:How to pass a context to another widget?如何将上下文传递给另一个小部件?
【发布时间】:2018-09-15 09:06:00
【问题描述】:

我正在通过flutter_local_notifications 为我的应用程序使用通知。我的应用由两个小部件组成。 FirstPage 和 SecondPage 小部件/类。我的 FirstPage 小部件的目的是显示将来会发生的警报/通知列表。而 SecondPage 小部件的目的是创建通知。

基本上,当我打开我的应用程序时,它会显示 FirstPage,然后我可以使用 Navigation pushNamed 导航到我的 SecondPage。

理想情况下,当我点击通知时,它会在 FirstPage 上显示一个对话框。

问题是,当我点击通知时,FirstPage 上没有显示任何内容,但是当我导航到 SecondPage 时,对话框出现在那里。

我尝试使用全局变量将我的 FirstPage 的上下文传递给 SecondPage 上的对话框:

BuildContext _contextOfFirst; // The global variable I used to store the context of FirstPage

...

class FirstPageState extends State<FirstPage> {

    ...

    @override
    Widget build(BuildContext context){
        _contextOfFirst = context; // FirstPage's context was stored on my global variable
    }

}

...

class SecondPageState extends State<SecondPage> {

    ...

    Future onselectNotification(String payload) async{

        print(_contextOfFirst); // Just for checking 

        showCupertinoDialog(
            context: _contextOfFirst, // I placed it here. Hoping that it will be displayed on the FirstPage
            builder: (_) => new CupertinoAlertDialog(
                title: new Text("Some Title"),
                content: new Text("$payload")
           )
        );
    }
...
}

即使我将 FirstPage 的上下文传递给对话框后,对话框仍然不会显示在 FirstPage 上,当我导航到 SecondPage 时,它​​会出现在那里。

我认为通过将 FirstPage 的上下文提供给对话框,它将使对话框出现在 FirstPage 上。但是我错了。

我很想知道我哪里出错了。

我会很感激你们的任何启发。

【问题讨论】:

  • 我认为我们应该将第一页作为通知的控制器,而将第二页仅作为助手,不是吗?
  • @Hovanes Mosoyan,感谢您的想法。我会努力做到的。

标签: android dart flutter


【解决方案1】:

您在第一个活动中显示通知并调用onselectNotification,您在第二个活动中显示对话框!这是没有意义的。

所以我建议您将 onselectNotification 放在 First class 中并作为 Callback 调用您的 Dialog 以显示并设置计时器或开启按钮点击你会显示第二个活动(如果你分享了@98​​7654323@的代码,我可以知道你想要实现什么样的场景)。

所以你的问题不是上下文问题,它只是调用指令的错误顺序。

【讨论】:

    猜你喜欢
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    相关资源
    最近更新 更多