【发布时间】:2019-03-10 03:45:36
【问题描述】:
我想在 StatefulWidget 中使用颤振通知与另一个 StatefulWidget 小部件进行通信。我在下面发布了一个示例,我觉得应该可以工作,但事实并非如此。当您单击“+”图标按钮时,它应该将通知发送到 subPage 小部件。目前,当您单击按钮时,似乎没有任何反应。我希望执行 onTitlePush() 函数。这是我第一次尝试通知,我必须有一些设置不正确。我在一个更大的应用程序中使用它,但下面的代码只是实现的一个示例。你能告诉我哪里出错了吗?
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;
}
}
【问题讨论】: