如何在 flutter 中从 class(小部件外部)打开屏幕
How to open a screen from a class (outside a widget) in flutter
所以,我的 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: Error: The getter 'context' isn't defined for the class 'NotPlugin'.
- 'NotPlugin' is from 'not_plugin.dart'.
Try correcting the name to the name of an existing getter, or defining a getter or field named 'context'.
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());)
error: The argument type 'Future' can't be assigned to the parameter type 'Future Function(String)'
您需要将 BuildContext 传递给您的函数:
void onClick(String payload, BuildContext context) {
//Do other things
Navigator.push(context, MaterialPageRoute(builder: (context) => LabMdScreen()));
}
所以,我的 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: Error: The getter 'context' isn't defined for the class 'NotPlugin'.
- 'NotPlugin' is from 'not_plugin.dart'. Try correcting the name to the name of an existing getter, or defining a getter or field named 'context'. 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());)
error: The argument type 'Future' can't be assigned to the parameter type 'Future Function(String)'
您需要将 BuildContext 传递给您的函数:
void onClick(String payload, BuildContext context) {
//Do other things
Navigator.push(context, MaterialPageRoute(builder: (context) => LabMdScreen()));
}