import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('监听'),
),
body: NotificationRoute(),
),
);
}
}
class NotificationRoute extends StatefulWidget {
@override
_NotificationRouteState createState() => _NotificationRouteState();
}
class _NotificationRouteState extends State<NotificationRoute> {
String _msg = '';
@override
Widget build(BuildContext context) {
return NotificationListener<MyNotification>(
onNotification: (notification) {
setState(() {
_msg += notification.msg + ' ';
});
},
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
// 通过Builder来构建RaisedButton,来获得按钮位置的context
Builder(
builder: (context) {
return RaisedButton(
onPressed: () => MyNotification('hi').dispatch(context),
child: Text('send notification'),
);
}
),
Text(_msg),
],
),
),
);
}
}
class MyNotification extends Notification {
MyNotification(this.msg);
final String msg;
}
网友评论