数据传输一般处理方式:自上而下的一层一层传递数据。
场景: WidgetB数据改变后,WidgetA也随之作出响应。
解决方案2:Notification,子节点状态变更,发送通知上报。
1.自定义notification
class TestNotification extends Notification {
TestNotification({
@required this.count,
});
final int count;
}
2.子节点发送通知
new RaisedButton(
textColor: Colors.black,
child: new Center(
child: new Text('点击传递随机数给上层Widget'),
),
onPressed: () {
new TestNotification(count: new Random().nextInt(100)).dispatch(key.currentContext);
})
3.父节点使用NotificationListener进行监听子节点发出的通知,并作出响应
new NotificationListener(
onNotification: (TestNotification n) {
scaffoldStateKey.currentState.showSnackBar(new SnackBar(content: new Text('随机数:${n.count}')));
return true;
},
child: new TestAPage(
key: key,
))
效果图

11.jpeg
每天学一点,学到Flutter发布正式版!
网友评论
<code>
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Notification Usage',
home: Scaffold(
appBar: AppBar(
title: Text('Notification Usage 2'),
),
body: NotificationPage(),
),
);
}
}
class TestNotification extends Notification {
TestNotification({
@required this.count,
});
final int count;
}
//HomePage
class NotificationPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _NotificationPageState();
}
}
class _NotificationPageState extends State<NotificationPage> {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
NotificationListener(
onNotification: (TestNotification n) {
Scaffold
.of(context)
.showSnackBar(SnackBar(content: Text('随机数:${n.count}')));
return true;
},
child: TestAPage(),
) //也是一个器件
],
);
}
}
class TestAPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _TestAPageState();
}
}
class _TestAPageState extends State<TestAPage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 10.0, top: 10.0, right: 10.0),
child: RaisedButton(
textColor: Colors.black,
child: Center(
child: Text('点击传递随机数给上层Widget 2'),
),
onPressed: () {
TestNotification(count: Random().nextInt(100))
.dispatch(context); //发送通知,类似Ext.fireEvent
}),
);
}
}
//EOP
</code>