《单页面使用》

在需要使用的页面来用。

比如说在,评论列表中更新数据,则我们就可以使用这样的方法来,在当页面操作数据不能共享。

  1. import 'package:YuWeiFlutterApp/src/customNotification.dart';
  2. import 'package:YuWeiFlutterApp/src/userbean.dart';
  3. import 'package:flutter/material.dart';
  4. class IndexInHeritedWidget extends StatefulWidget {
  5. @override
  6. _IndexInHeritedWidgetState createState() => _IndexInHeritedWidgetState();
  7. }
  8. class _IndexInHeritedWidgetState extends State<IndexInHeritedWidget> {
  9. UserBean userBean = UserBean(name: "default", address: "default");
  10. num i = 1;
  11. @override
  12. Widget build(BuildContext context) {
  13. print("page1");
  14. return Scaffold(
  15. appBar: AppBar(
  16. title: Text("Page_1"),
  17. ),
  18. body: NotificationListener<CustomNotification>(
  19. ///CustomNotification(UserBean(
  20. /// name : "Flutter custom Notification",
  21. /// address: "China")
  22. ///).dispatch(context);
  23. onNotification: (data){ // data 是监听 CustomNotification 变化的数据,如下面改变了的
  24. userBean = data.userBean;
  25. setState(() {
  26. });
  27. return true;
  28. },
  29. child : Builder(
  30. builder: (context) => Container(
  31. width: double.infinity,
  32. height: double.infinity,
  33. color: Color(0x88f1f1f1),
  34. child: Column(
  35. children: [
  36. SizedBox(height: 10.0,),
  37. Text( userBean.name ),
  38. SizedBox(height: 10.0,),
  39. Text( userBean.address ),
  40. SizedBox(height: 200.0,),
  41. FloatingActionButton(
  42. onPressed: (){
  43. CustomNotification(UserBean(
  44. name : "Flutter custom Notification $i",
  45. address: "China $i")
  46. ).dispatch(context);
  47. /// 当 dispatch 的时候我们就会往上找,直到找到NotificationListener的onNotification然后改变值。
  48. setState(() {
  49. i++;
  50. });
  51. },
  52. child: Icon(Icons.add_alert_outlined),
  53. ),
  54. SizedBox(height: 200.0,),
  55. ],
  56. ),
  57. ),
  58. )
  59. ),
  60. );
  61. }
  62. }

CustomNotification

  1. import 'package:YuWeiFlutterApp/src/userbean.dart';
  2. import 'package:flutter/material.dart';
  3. // Notification
  4. class CustomNotification extends Notification {
  5. UserBean userBean;
  6. CustomNotification(this.userBean);
  7. }