【问题标题】:How to open a screen from a class (outside a widget) in flutter如何在颤动中从类(小部件外部)打开屏幕
【发布时间】:2021-03-01 00:35:05
【问题描述】:

所以,我的 lab_widget 有一个普通按钮,它从另一个名为 not_plugin 的文件中调用一个函数。我希望每次单击按钮时,not_pugin 中的函数都会打开一个确定的屏幕。这就是我在 not_plugin 中的内容:


Future<dynamic> onClick(String payload) async {
     //Do other things

     Navigator.push(context, MaterialPageRoute(builder: (context) => LabMdScreen()));
}

但它会引发以下错误:

46:24:错误:没有为类“NotPlugin”定义吸气剂“上下文”。

  • “NotPlugin”来自“not_plugin.dart”。 尝试将名称更正为现有 getter 的名称,或定义一个名为“context”的 getter 或字段。 Navigator.push(context, MaterialPageRoute(builder: (context) => MyScreen()));

那么我该如何解决呢?

更新

传递一个 BuildContext 后,在另一个函数中抛出此错误:

Future<void> initLocalNotification() async {
    androidInitializationSettings =
        AndroidInitializationSettings('@mipmap/ic_launcher');//here
    iosInitializationSettings = IOSInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification);
    initializationSettings = InitializationSettings(
        android: androidInitializationSettings, iOS: iosInitializationSettings);

    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onClick());
  }

在最后一行(onSelectNotification: onClick());)

错误:无法将参数类型“Future”分配给参数类型“Future Function(String)”

【问题讨论】:

    标签: flutter dart widget


    【解决方案1】:

    您需要将 BuildContext 传递给您的函数:

    void onClick(String payload, BuildContext context) {
         //Do other things
    
         Navigator.push(context, MaterialPageRoute(builder: (context) => LabMdScreen()));
    }
    

    【讨论】:

    • 错误:参数类型“Future Function(String, BuildContext)”不能分配给参数类型“Future Function(String)”。
    • 为什么你的函数是异步的?
    • 你是否传递了调用这个函数的上下文和这个类中的导入材料?
    • 是的,但是我有另一个函数正在抛出,我会更新问题给你看
    • 我还是看不到你在哪里调用了onClick函数,你能说明你在哪里调用这个函数吗?
    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多