I am trying to do push notification on realtime database firebase by using cloud function with flutter app but got this error after deploy. And I am not sure that code right or not because I am not really understanding the flow. I already successfully insert data to database and the problem is to using cloud function to send notification that data onchange to app back.
[2022-08-20T05:04:16.312Z] @firebase/database: FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND"."}
here code on my cloud function
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.notifyTrigger =
functions.database.ref("Users/{uid}").onCreate((snapshot, context) => {
if (snapshot.empty) {
console.log("No Devices");
return;
}
});
const payload = {
notification: {
title: "Message from Cloud",
body: "This is your body",
badge: "1",
sound: "default",
},
};
return admin.database().ref("Users").once("value").then((allToken) => {
if (allToken.val()) {
console.log("token available");
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payload);
} else {
console.log("No token available");
}
});
this is from my flutter app main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'firebase_options.dart';
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description: 'This channel is used for important notifications.',
// description
importance: Importance.high,
playSound: true);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print('A bg message just showed up : ${message.messageId}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Push Notification',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Firebase Push Notification'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final userNameController = TextEditingController();
final userAgeController = TextEditingController();
final userSalaryController = TextEditingController();
DatabaseReference dbRef;
_getToken(){
FirebaseMessaging.instance.getToken().then((deviceToken){
print("Device Token: $deviceToken");
});
}
int _counter = 0;
@override
void initState() {
super.initState();
_getToken();
dbRef = FirebaseDatabase.instance.ref().child('Users');
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('onMessage: $message');
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
color: Colors.blue,
playSound: true,
icon: '@mipmap/ic_launcher',
),
));
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('A new onMessageOpenedApp event was published!');
print('onMessage: $message');
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null) {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text(notification.title),
content: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [Text(notification.body)],
),
),
);
});
}
});
}
void showNotification() {
setState(() {
_counter++;
});
flutterLocalNotificationsPlugin.show(
0,
"Testing $_counter",
"How you doin ?",
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
channelDescription: channel.description,
importance: Importance.high,
color: Colors.blue,
playSound: true,
icon: '@mipmap/ic_launcher')));
}
@override
Widget build(BuildContext context) {
bool showFab = MediaQuery.of(context).viewInsets.bottom != 0;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
title: Text(widget.title),
centerTitle: true,
),
body: Center(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
const SizedBox(
height: 20,
),
const Text(
'You have pushed the button this many times:',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400,
),
textAlign: TextAlign.center,
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
const SizedBox(
height: 50,
),
TextField(
controller: userNameController,
keyboardType: TextInputType.text,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Name',
hintText: 'Enter Your Name',
),
),
const SizedBox(
height: 30,
),
TextField(
controller: userAgeController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Age',
hintText: 'Enter Your Age',
),
),
const SizedBox(
height: 30,
),
MaterialButton(
onPressed: () {
Map<String, String> users = {
'name': userNameController.text,
'age': userAgeController.text,
};
dbRef.push().set(users);
userNameController.clear();
userAgeController.clear();
},
color: Colors.orange[700],
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
minWidth: 300,
height: 45,
child: const Text('Insert Data to Firebase'),
),
],
),
),
),
),
floatingActionButton: Visibility(
visible: !showFab,
child: buildMessageButton(),
),// This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget buildMessageButton() => FloatingActionButton.extended(
backgroundColor: Colors.teal,
icon: Icon(Icons.notifications),
onPressed: showNotification,
tooltip: 'Increment', label: Text('Test Local Notification'),
);
}
Here image of my flutter app

But I am not really get it what is my column name in firebase database because the column show token instead of column name. So I just try like this
functions.database.ref("Users/{uid}")