Code Monkey home page Code Monkey logo

Comments (9)

TarekkMA avatar TarekkMA commented on July 22, 2024

@mklepaczko Thank you for reporting this issue. I've run the FlutterFire messaging example app found here. The getToken(vapidKey: ...) works without issue. Can you share a minimal reproducible example app where this issue occurs?

Also, please try using the latest Flutter version and the latest firebase_messaging version.

from flutterfire.

mklepaczko avatar mklepaczko commented on July 22, 2024

Hi, thanks for your answer.

i just updated to Flutter 3.22.2 but still the same.

Here is a sample app configured with firebase:

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_web_frame/flutter_web_frame.dart';
import 'package:projekty_dev/firebase_options.dart';

void main() async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  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 FlutterWebFrame(
      builder: (context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            // This is the theme of your application.
            //
            // TRY THIS: Try running your application with "flutter run". You'll see
            // the application has a blue toolbar. Then, without quitting the app,
            // try changing the seedColor in the colorScheme below to Colors.green
            // and then invoke "hot reload" (save your changes or press the "hot
            // reload" button in a Flutter-supported IDE, or press "r" if you used
            // the command line to start the app).
            //
            // Notice that the counter didn't reset back to zero; the application
            // state is not lost during the reload. To reset the state, use hot
            // restart instead.
            //
            // This works for code too, not just values: Most code changes can be
            // tested with just a hot reload.
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      },
      maximumSize: const Size(800, 800),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  Future messagingPermissions() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );
    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      debugPrint('User granted permission');
      FirebaseMessaging.instance.getToken(
        vapidKey:
            'BKE0htV7ksYElGdkn9Xi-eCchkhnsWJceIOeuQkI2qK7M7fq4HivEZ7opk-2-4VqVHC0SBY_GDedAAGfjiWilqs');
    } else {
      debugPrint('User declined or has not yet granted permission');
    }
    
  }

  @override
  Widget build(BuildContext context) {
    messagingPermissions();
    final double width = MediaQuery.of(context).size.width;
    final double height = MediaQuery.of(context).size.height;
    debugPrint('Screen is of $height height and $width width');
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.

    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

The error comes in this file
/firebase_messaging_web-3.8.10/lib/src/interop/messaging.dart

Future<String> getToken({String? vapidKey}) async {
    try {
      final token = ((await messaging_interop
              .getToken(
                  jsObject,
                  vapidKey == null
                      ? null
                      : messaging_interop.GetTokenOptions(
                          vapidKey: vapidKey.toJS))
              .toDart)! as JSString) // here the error is highlited
          .toDart;
      return token;
    } catch (err) {
      // A race condition can happen in which the service worker get registered
      // only when getToken is called. In this case, the first call to getToken
      // might fail.
      if (err.toString().toLowerCase().contains('no active service worker') &&
          firstGetTokenCall) {
        firstGetTokenCall = false;
        return getToken(vapidKey: vapidKey);
      }
      rethrow;
    }
  }

from flutterfire.

TarekkMA avatar TarekkMA commented on July 22, 2024

I've replicated the code here: https://github.com/firebase/flutterfire/tree/issue/13010 and it works without issues. One possible cause for your issue could be an incorrect vapidKey. Can you check if you have the correct key?

from flutterfire.

mklepaczko avatar mklepaczko commented on July 22, 2024

Ok I'm confused now and don't know where to look for the bug

It's ot an app code problem as it works with you

I create a new Vapid key to be sure, same problem

I connected the app to a different Firestore project and created a new key, same problem.

i created a new project and new VapidKey, same problem

What can I do next? any JS packages or similar to update? I just updated Flutter to the last version.

As for information getToken() works fine on IOS.

from flutterfire.

TarekkMA avatar TarekkMA commented on July 22, 2024

@mklepaczko Can you try to run the example app from the linked branch and see if it's also causing issues? Additionally, could you try surrounding the erroring code with a try-catch block and print the error?

from flutterfire.

mklepaczko avatar mklepaczko commented on July 22, 2024

Will try that. The error is above in the "Relevant log output"

from flutterfire.

google-oss-bot avatar google-oss-bot commented on July 22, 2024

Hey @mklepaczko. We need more information to resolve this issue but there hasn't been an update in 7 weekdays. I'm marking the issue as stale and if there are no new updates in the next 7 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

from flutterfire.

andynewman10 avatar andynewman10 commented on July 22, 2024

I already got this error and I believe it is intermittent. Yesterday I submitted an unrelated issue and experienced the problem described in this page on Chrome on macOS. I'm almost sure it did that 3-4 times, then the problem disappeared.
I experienced the problem with the flutterfire example app (https://github.com/firebase/flutterfire/tree/master/packages/firebase_messaging/firebase_messaging/example)

from flutterfire.

andynewman10 avatar andynewman10 commented on July 22, 2024

I confirm the problem is intermittent.

I just tested on Google Chrome, latest version on macOS Ventura. I used the flutterfire example app (see above for the link), and the problem occurred multiple times until it (eventually!) worked, displaying the FCM token.

from flutterfire.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.