更新时间:2023-02-26 21:17:49
我想您知道如何将 firebase 添加到您的应用程序中.如果没有:https://firebase.google.com/docs/flutter/setup?platform=android
I suppose that you know how to add firebase to your App. If not: https://firebase.google.com/docs/flutter/setup?platform=android
将firebase添加到应用程序后,这就是我所做的:
After adding firebase to the App, this is what I do :
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
routes: {
'/': (context) => AppStarter(),
'/message': (context) => NotificationDetails(),
},
),
);
}
class AppStarter extends StatefulWidget{
@override
_AppStarterState createState() => _AppStarterState();
}
class _AppStarterState extends State<AppStarter>
{
FirebaseMessaging messaging = FirebaseMessaging.instance;
Future<void> showMeMyToken()
async {
var myToken = await messaging.getToken();
print("My Token is: " + myToken.toString());
}
@override
void initState() {
super.initState();
showMeMyToken();
FirebaseMessaging.instance.getInitialMessage().then((value) {
if(value != null)
{
Navigator.push(context,
MaterialPageRoute(
builder: (context){return NotificationDetails();},
settings: RouteSettings(arguments: value.data,),
),
);
}
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (message.notification != null) {
print('Message on Foreground: ${message.notification}');
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message)
{
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {return NotificationDetails();},
settings: RouteSettings(arguments: message.data,)
),
);
});
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Just a Test',
home: AppHome(),
);
}
}
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print("Handling a background message :-): ${message.data}");
//Here you can do what you want with the message :-)
}