Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Use Notification to message other widgets

Tags:

flutter

dart

I would like to use a flutter Notification in a StatefulWidget to communicate with another StatefulWidget widget. I have posted an example below that I feel should be working but it does not. When you click the "+" icon button, it should send out the notification to the subPage widget. Currently, when you click the button, nothing seems to happen. I would expect the onTitlePush() function to be executed. This is my first time trying Notifications and I must have something set up incorrectly. I am using this in a larger app but the code below is just a sample of the implementation. Could you let me know where I went wrong?

import 'package:flutter/material.dart';

void main() => runApp(TestApp());

class TestApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Notificaton Test',
      home: MainPage(),
    );
  }
}

class MyNotification extends Notification {
  final String title;

  const MyNotification({this.title});
}

class MainPage extends StatefulWidget {
  @override
  MainPageState createState() {
    return new MainPageState();
  }
}

class MainPageState extends State<MainPage> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Basic AppBar'),
          actions: <Widget>[
            // action button
            IconButton(
              icon: new Icon(Icons.add),
              onPressed: () {
                MyNotification(title: "Updated Text!")..dispatch(context);
              },
            ),
            // action button
          ],
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: new SubPage(),
        ),
      ),
    );
  }
}

class SubPage extends StatefulWidget {
  @override
  SubPageState createState() {
    return new SubPageState();
  }
}

class SubPageState extends State<SubPage> {
  String _text = "Click the Plus Icon";
  @override
  Widget build(BuildContext context) {
    return NotificationListener<MyNotification>(
      onNotification: onTitlePush,
      child: new Center(
          child: new Text(_text, style: new TextStyle(fontSize: 40.0))
      ),
    );
  }
  bool onTitlePush(MyNotification notification) {
    print("New item ${notification.title}");

    setState(() { _text = notification.title; });
    return true;
  }
}
like image 269
casmang Avatar asked Oct 04 '18 16:10

casmang


People also ask

How do you send notifications to other users on Flutter?

This can simply be done by heading to your Firebase project > Project Settings > Cloud Messaging then copy the API key under Cloud Messaging API (Legacy) . When you have your Firebase Cloud Messaging API key, this is the code to display a notification given the notification title, body, and device token to send it to.

How do I notify widgets in Flutter?

To listen for notifications in a subtree, use a NotificationListener. To send a notification, call dispatch on the notification you wish to send. The notification will be delivered to any NotificationListener widgets with the appropriate type parameters that are ancestors of the given BuildContext.

How do you handle notifications when an app is in foreground in Firebase Flutter?

To handle messages while your application is in the foreground, listen to the onMessage stream. }); The stream contains a RemoteMessage , detailing various information about the payload, such as where it was from, the unique ID, sent time, whether it contained a notification and more.


1 Answers

Notifications are the opposite of BuildContext. With notifications, it is children that sends value to their parents.

Notifications are not global. Widgets that are not parent of the dispatcher cannot listen to the said notification.

Therefore, what you are trying to achieve in fact cannot be done with notifications.

There are a few alternatives:

  • Use Listenable such as ValueListenable How to set state from another widget?
  • Use Streams Trigger a function from a widget to a State object
  • Refactor your Widget tree so that listeners are parents of the dispatcher
like image 55
Rémi Rousselet Avatar answered Oct 19 '22 19:10

Rémi Rousselet