Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access Variable form another class in top level function Flutter

I have a background notification handler in my flutter app, which is a top-level function like so:

Future<void> _onBackgroundMessage(RemoteMessage message) async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  final chatClient = StreamChatClient(STREAM_API_KEY);

  print(Utils.user?.uid);
  print(Utils.user?.streamToken);

  chatClient.connectUser(
    su.User(id: Utils.user?.uid ?? ''),
    Utils.user?.streamToken ?? '',
    connectWebSocket: false,
  );

  NotificationUtils.handleGetStreamNotification(message, chatClient);

  SharedPreferences prefs = await SharedPreferences.getInstance();
  int appBadgeCounter = prefs.getInt(appBadgePrefsKey) ?? 0;
  FlutterAppBadger.updateBadgeCount(appBadgeCounter + 1);
}

In the notification handler, I need to connect to a separate server using a uid and a token. I have a Utils singleton class where I store an app user as a variable. I initialize this Utils app variable in my home page stateful widget class and persist it throughout the app. This way, I can minimize my number of database calls for user data.

However, in this top-level notification handler, the Utils.user is always null. This top level function exists in my home page stateful widget class, but it is a top level function still.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to avoid making database calls for every single notification that the app receives. Is there a way to get this Utils. user data without getting null??

>Solution :

you have to setUser before using it in chatClient.connectUser and along with you can check if user is null or not if null initialize it then it stops does not make extra calls.

 Future<void> _onBackgroundMessage(RemoteMessage message) async {
  ...
  await Firebase.initializeApp();
  final chatClient = StreamChatClient(STREAM_API_KEY);
  
   if(Utils.user != null) {
      Utils.setUser(); 
   }

  print(Utils.user?.uid);
  print(Utils.user?.streamToken);
  ...
 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading