簡體   English   中英

如何將上下文傳遞給另一個小部件?

[英]How to pass a context to another widget?

我正在使用帶有flutter_local_notifications的應用程序通知。 我的應用程序包含兩個小部件。 FirstPage和SecondPage小部件/類。 我的FirstPage小部件的目的是顯示將來會發生的警報/通知列表。 而SecondPage小部件的目的是創建通知。

基本上,當我打開我的應用程序時,它將顯示FirstPage,然后可以使用Navigation pushNamed導航到我的SecondPage。

理想情況下,當我點擊通知時,它將在FirstPage上顯示一個對話框。

問題是,當我點擊通知時,第一頁上什么都沒有顯示,但是當我導航至第二頁時,對話框出現了。

我試圖使用全局變量將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上。 但是我錯了。

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

謝謝你們的啟發。

您將在第一個活動中顯示通知,並在第二個活動中顯示對話框的位置調用onselectNotification 這沒有意義。

因此,我建議您將onselectNotification放置在First類中,並作為Callback調用您的Dialog來顯示,然后設置計時器或按一下按鈕即可顯示第二個活動 (如果您共享showCupertinoDialog的代碼,我知道您正在嘗試實現哪種方案)。

因此,您的問題不是上下文問題,這只是調用指令的錯誤順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM