0

I am writing a Flutter app that uses a Global Function to handle Pushy.me notifications. This function needs to update a stateful widget's state.

I have tried a Global Key to access the widgets current state but it did nothing. I have tried an Eventify emitter, the emit and the listener didnt seem to line up.

import 'package:eventify/eventify.dart';

EventEmitter emitter = new EventEmitter();
GlobalKey<_WrapperScreenState> _key = GlobalKey<_WrapperScreenState>();

void backgroundNotificationListener(Map<String, dynamic> data) {
  // Print notification payload data
  print('Received notification: $data');

  // Notification title
  String notificationTitle = 'MyApp';

  // Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
  String notificationText = data['message'] ?? 'Hello World!';

  Pushy.notify(notificationTitle, notificationText, data);
  emitter.emit('updateList',null,"");
  try{
    print(_key.currentState.test);
  }
  catch(e){
    print(e);
  }
  // Clear iOS app badge number
  Pushy.clearBadge();
}
class WrapperScreen extends StatefulWidget {
  @override
  _WrapperScreenState createState() => _WrapperScreenState();
}
Ian Brown
  • 69
  • 12
  • An unusual alternative would be to create a singleton class that would hold the type of data you need, so you would update the singleton at the same time that your widget consumes it. Another (recommended) alternative would be to build architecture with global state management. – Chance Sep 19 '20 at 04:55
  • @JustCase I tried today to switch to using Provider with ChangeNotifiers. This would give me more of a global state that could be updated in more places. The issue now is a the global function does not seem to have access to Context and if I create a variable to the watcher as a global variable it is still null when called inside the function. It seems that the function is declared before the variable is set and it never sees the updated value of the variable... any thoughts? – Ian Brown Sep 20 '20 at 07:59

1 Answers1

0

You can try using events for this, using a StreamController or the event bus package. Your stateful widget would listen on a global event bus, and you can fire an event with the necessary information for the widget itself to use to update the state.

Something like this (using the event bus package):

// main.dart

EventBus eventBus = EventBus();


class MyEvent {}

void somewhereGlobal() {
    // trigger widget state change from global location
    eventBus.fire(MyEvent());
}


void main() {

...

}

// my_stateful_widget.dart
...

class _MyWidgetState extends State<MyWidget> {
  @override
  void initState() {
    super.initState();
    eventBus.on<MyEvent>().listen((event) {
      // update widget state
      print("update widget state");
    });
  }

...