Skip to content

Instantly share code, notes, and snippets.

@xyclos
Created May 7, 2023 02:03
Show Gist options
  • Save xyclos/93535c809ca2d733f80e98ead3529a33 to your computer and use it in GitHub Desktop.
Save xyclos/93535c809ca2d733f80e98ead3529a33 to your computer and use it in GitHub Desktop.
basic flutter FCM example
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await FirebaseMessaging.instance.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
String? _token;
@override
void initState() {
super.initState();
firebaseMessaging.getToken().then((token) => setState(() {
debugPrint('!!! token $token');
_token = token;
}));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Here is your token:',
),
Text(
'$_token',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment