我正尝试使用Firebase云评估,并且在此过程中,我只想在推送通知到达时向用户显示弹出对话框。但是为了显示对话,我们需要上下文对象,因为showDialog
的参数之一是BuildContext
。
我尝试了很多方法,但是没有用。到目前为止,我的代码如下所示:
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
print('onMessage: $message');
return;
},
onBackgroundMessage: myBackgroundMessageHandler,
onResume: (Map<String, dynamic> message) {
print('onResume: $message');
return;
},
onLaunch: (Map<String, dynamic> message) {
print('onLaunch: $message');
Text('onLaunch: $message'),
);
return;
});
注意:该代码是在一个单独的类中编写的,我正在尝试在没有任何第三部分库的情况下实现它。
答案 0 :(得分:0)
首先,如果没有有效的上下文,您将无法显示对话框。
您为什么不像这样简单地将BuildContext
传递给您的班级?
class SeparateClass {
final BuildContext context;
SeparateClass(this.context);
void configure() {
// your rest of the configuration code
// you can use showDialog(context, ...) here
}
}
答案 1 :(得分:0)
我解决了一个类似的问题,该问题显示了SnackBar而不是Dialog。使用此代码,您可以在应用程序中的任意位置启动SnackBar或对话框。
import 'package:collectio/pages/init_screen_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'helper.dart';
void main() {
Provider.debugCheckInvalidValueType = null;
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
// here the context refers to MaterialApp widget,
// you can´t call Scaffold.of(context)
body: Builder(builder: (context) {
// here the context refers to Scaffold widget
Helper.startFirebaseMessaging(context);
return InitScreenPage();
}),
));
}
}
class Helper {
static startFirebaseMessaging(BuildContext buildContext) {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
var notification = message['notification'];
// build the snackbar
final snackBar = SnackBar(
content: Text(notification['title']),
action: SnackBarAction(
label: 'Ok',
onPressed: (){}
),
);
try {
Scaffold.of(buildContext).showSnackBar(snackBar);
} catch (e) {
print(e);
}
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
_firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(
sound: true, badge: true, alert: true, provisional: true));
_firebaseMessaging.onIosSettingsRegistered
.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
_firebaseMessaging.getToken().then((String token) {
assert(token != null);
print("Push Messaging token: $token");;
});
print("Waiting for token...");
}
}
也许您可以将其应用于您的代码。