0

Si me pueden dar una mano. Estoy trabajando con Flutter y firebase con flutter_local_notifications: ^13.0.0 y firebase_messaging: ^14.3.0.

No están llegando las notificaciones enviadas cuando la app se instala por primera vez en el teléfono Android que seria la app del cliente. Pero si de esa app se envía una notificación después de eso si empiezan a llegar las notificación cuando es enviado desde la app del admin.

Unas de las cosas que pienso que puede ser es que al inicializar no esta conectando en firebase y solamente al enviar la notificacion para todas app ahi se conecta correctamente a firebase.

main.dart

 const AndroidNotificationChannel channel = AndroidNotificationChannel(
        'high_importance_channel', // id
        'High Importance Notifications', // title
        //   '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();
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    
      await flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              AndroidFlutterLocalNotificationsPlugin>()
          ?.createNotificationChannel(channel);
    
      await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
        alert: true,
        badge: true,
        sound: true,
      );
      runApp(const MyApp());
    }
    
 
 
    
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key});
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      late TextEditingController _textToken;
      late TextEditingController _textSetToken;
      late TextEditingController _textTitle;
      late TextEditingController _textBody;
    
      @override
      void dispose() {
        _textToken.dispose();
        _textTitle.dispose();
        _textBody.dispose();
        _textSetToken.dispose();
        super.dispose();
      }
    
      @override
      void didChangeDependencies() {
        super.didChangeDependencies();
      }
    
      @override
      void initState() {
        super.initState();
    
        _textToken = TextEditingController();
        _textSetToken = TextEditingController();
        _textTitle = TextEditingController();
        _textBody = TextEditingController();
    
        FirebaseMessaging.onMessage.listen((RemoteMessage message) {
          RemoteNotification? notification = message.notification;
          AndroidNotification? android = message.notification?.android;
          if (android != null) {
            flutterLocalNotificationsPlugin.show(
                notification.hashCode,
                notification!.title,
                notification.body,
                NotificationDetails(
                  android: AndroidNotificationDetails(
                      channel.id, channel.name, // channel.description,
                      color: Colors.blue,
                      playSound: true,
                      icon: '@mipmap/ic_launcher'),
                ));
          }
        });
      }
    
     
      Future<bool> pushNotificationsSpecificDevice({
        required String token,
        required String title,
        required String body,
      }) async {
        String dataNotifications = '{ "to" : "$token",'
            ' "notification" : {'
            ' "title":"$title",'
            '"body":"$body"'
            ' }'
            ' }';
    
        await http.post(
          Uri.parse(Constants.BASE_URL),
          headers: <String, String>{
            'Content-Type': 'application/json',
            'Authorization': 'key= ${Constants.KEY_SERVER}',
          },
          body: dataNotifications,
        );
        return true;
      }
    
      Future<bool> pushNotificationsGroupDevice({
        required String title,
        required String body,
      }) async {
        String dataNotifications = '{'
            '"operation": "create",'
            '"notification_key_name": "appUser-testUser",'
            '"registration_ids":cofigo
            '"notification" : {'
            '"title":"$title",'
            '"body":"$body"'
            ' }'
            ' }';
    
        var response = await http.post(
          Uri.parse(Constants.BASE_URL),
          headers: <String, String>{
            'Content-Type': 'application/json',
            'Authorization': 'key= ${Constants.KEY_SERVER}',
            'project_id': Constants.SENDER_ID
          },
          body: dataNotifications,
        );
    
        print(response.body.toString());
    
        return true;
      }
    
      Future<bool> pushNotificationsAllUsers({
        required String title,
        required String body,
      }) async {
        FirebaseMessaging.instance.subscribeToTopic("myTopic1");
    
        String dataNotifications = '{ '
            ' "to" : "/topics/myTopic1" , '
            ' "notification" : {'
            ' "title":"$title" , '
            ' "body":"$body" '
            ' } '
            ' } ';
    
        var response = await http.post(
          Uri.parse(Constants.BASE_URL),
          headers: <String, String>{
            'Content-Type': 'application/json',
            'Authorization': 'key= ${Constants.KEY_SERVER}',
          },
          body: dataNotifications,
        );
        print(response.body.toString());
        return true;
      }
    
      Future<String> token() async {
        return await FirebaseMessaging.instance.getToken() ?? "";
      }
    
      void showNotification() {
        setState(() {
          _counter++;
        });
        flutterLocalNotificationsPlugin.show(
            0,
            "Testing $_counter",
            "How you doin ?",
            NotificationDetails(
                android: AndroidNotificationDetails(
                    channel.id, channel.name, //channel.description,
                    importance: Importance.high,
                    color: Colors.blue,
                    playSound: true,
                    icon: '@mipmap/ic_launcher')));
      }
    
      bool check() {
        if (_textTitle.text.isNotEmpty && _textBody.text.isNotEmpty) {
          return true;
        }
        return false;
      }
    }

Otras formas que intente y tenia los mismos resultados seria.

void sendPushMessage(String token,String title, String body ) async {
    //FirebaseMessaging.instance.subscribeToTopic("myTopic1");
    FirebaseMessaging.instance.subscribeToTopic("myTopic1");
    try {
      await http.post(
        Uri.parse('https://fcm.googleapis.com/fcm/send'),
        headers: <String, String>{
          'Content-Type': 'application/json',
          'Authorization':
              'key=Key'
        },
        body: jsonEncode(
          <String, dynamic>{
            'priority': 'high',
            'data': <String, dynamic>{
              'click_action': 'FLUTTER_NOTIFICATION_CLICK',
              'status': 'done',
              'title': title,
              'body': body,
            },
            "notification": <String, dynamic>{
              "title": title,
              "body": body,
              "android_channel_id": "dbfood"
            },
           // "to": token,
            "priority": "high",
            "to": "/topics/myTopic1"
         //   "to": "diRoD1CkRu29xyOjrkp_7D:APA91bFjZ26HaHSyPivrbKpaoDl8IxM2Q0zjFrcYZ2jyd_HXDV8JEsDrrYzJRJYugvbNkquSHmbVXjEwp6OZxwYRm9KUO5e_PxC1hfCp1l7wmQP5YOCMEvB7Kf727r54Lxk7isRr2bhY"


          },
        ),
      );
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

El error pereciste ya se autorizo en el AndroidManifest.xml. El problema es solo cuando se instala por primera vez en el teléfono ya que cuando se enviar de la app cliente la notificación funciona correctamente en primer plano, segundo y cuando esta cerrada la app. Estuve buscando ya por varios días la respuesta y aun no encuentro nada.

Agradezco su ayuda.

2
  • Hola, para poder ayudarte con tu problema, necesitaría conocer un poco más acerca del problema que estás experimentando. ¿Podrías proporcionar más información acerca de las notificaciones que no están llegando en la app del cliente? ¿Hay algún mensaje de error o alguna información relevante que puedas proporcionar?
    – sandiooo
    el 18 mar. a las 17:07
  • Como estas!! No sale ningún mensaje en la consola. Pero una vez que de la app del cliente se envía la notificación para todos ahí sin problemas llegan las notificaciones enviadas de la app del admin. Creo que puede ser algo en la inicializacion que no esta arrancando o no se conecta con firebase. el 18 mar. a las 22:22

0

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

Examina otras preguntas con la etiqueta o formula tu propia pregunta.