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