casmang
casmang

Reputation: 405

Flutter - Use Notification to message other widgets

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;
  }
}

Upvotes: 12

Views: 15662

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277727

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:

Upvotes: 23

Related Questions