我解决了一个类似的问题,它显示了一个 SnackBar 而不是一个对话框。使用此代码,您可以在应用程序中的任何位置启动 SnackBar 或 Dialog。
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...");
}
}
也许您可以将其应用于您的代码。