Flutter has searched a lot of information. For now, no page similar to Android/iOS has been found to broadcast notifications and values. Please let me know if there are any comments

Why do I need to broadcast notification?

Suppose there is a requirement that the navigation has three pages, the first page has a button to jump to the second page, the second page has a button to jump to the third page, and the third page has a button to change the background color of the first page. In this case, you can send the value by notification. Add a notification listener to the first page and send notifications to the third page to inform the first page.

GIF:

Train of thought

My idea is to create a singleton class that creates this listener on the page you want to listen to. The singleton class continues to be created on the page where the notification needs to be sent, passing the value through a callback.

code

Create a singleton class

typedef GetObject = Function(dynamic object); Class NotificationCenter {// Factory mode Factory NotificationCenter() => _getInstance(); static NotificationCenter get instance => _getInstance(); static NotificationCenter _instance; NotificationCenter._internal() {// initialize} static NotificationCenter_getInstance() {
    if (_instance == null) {
      _instance = new NotificationCenter._internal();
    }
    return_instance; } // create a Map to record the name Map<String, dynamic> postNameMap = Map<String, dynamic>(); GetObject getObject; // Add listener method addObserver(String postName, object(Dynamic Object)) {postNameMap[postName] = null; getObject = object; } postNotification(String postName, dynamic object) {// Check whether the Map contains postNameif(postNameMap.containsKey(postName)) { postNameMap[postName] = object; getObject(postNameMap[postName]); }}}Copy the code

Add a listener on the home page

/ / add listeners NotificationCenter. Instance. AddObserver ('changColor', (object){

  setState(() {

    backColor = object;
  });
});
Copy the code

Send notifications on page 3

/ / notice. The first page background color into red NotificationCenter instance. PostNotification ('changColor', Colors.red);

Copy the code

The last

The code may be poorly written, just providing an idea.