Flutter笔记--通知

这一节回顾一下Flutter中的Notification,Notification(通知)是Flutter中一个重要的机制,在widget树中,每一个节点都可以分发通知,通知会沿着当前节点向上传递,所有父节点都可以通过NotificationListener来监听通知,通过它可以实现跨组件的事件传递,使应用变得更加灵活。

主要步骤包括:

1 创建NotificationListener:在需要监听通知的Widget的build方法中,创建NotificationListener实例。

2 设置onNotification回调函数:NotificationListener需要一个onNotification回调函数,用于处理接收到的通知。在回调函数中,可以编写逻辑来处理不同类型的通知。

3 指定子Widget:将需要被监听通知的Widget作为NotificationListener的子Widget。

栗子:

Dart 复制代码
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class NotificationTest extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _NotificationTest();
  }
}

class _NotificationTest extends State<NotificationTest> {
  int _progress = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification notification) {
          if(notification is ScrollStartNotification) {
            print('开始滚动...');
          } else if(notification is ScrollUpdateNotification) {
            final currentPixel = notification.metrics.pixels;
            final totalPixel = notification.metrics.maxScrollExtent;
            double progress = currentPixel / totalPixel;
            setState(() {
              _progress = (progress * 100).toInt();
              print('滚动..._progress:$_progress');
            });
            print('正在滚动: ${currentPixel} - ${totalPixel}');
          } else if(notification is ScrollEndNotification) {
            print('结束滚动...');
          }
           //  返回false表示不阻止事件继续向上冒泡  
           return false;
        },
        child: Stack(
          alignment: Alignment.bottomRight,
          children: [
            ListView.builder(
                itemCount: 100,
                itemExtent: 60,
                itemBuilder: (BuildContext context,int index) {
                  return ListTile(title: Text("Item $index"),);
                })
          ],
        )),);
  }

}

通知冒泡:

1 通知的发起:在Flutter的Widget树中,任何节点都可以分发通知。这通常通过调用Notification.dispatch(context)方法实现,其中context是当前节点的上下文信息。

dispatch方法会调用context.visitAncestorElements(visitAncestor),这个方法会向上遍历父元素,并对每个父元素执行visitAncestor回调。

2 通知的传递:通知从子节点开始,沿着Widget树向上传递,在传递过程中,每个父节点都有机会通过NotificationListener组件来监听这些通知。

  1. 通知的中止:通知冒泡可以中止。如果在NotificationListener的onNotification回调中返回true,则表示当前节点已经处理了通知,并决定不再向上传递。如果返回false,则通知会继续向上传递,直到遇到下一个NotificationListener或到达Widget树的顶部。
相关推荐
孤鸿玉4 小时前
Fluter InteractiveViewer 与ScrollView滑动冲突问题解决
flutter
使一颗心免于哀伤10 小时前
《设计模式之禅》笔记摘录 - 21.状态模式
笔记·设计模式
叽哥10 小时前
Flutter Riverpod上手指南
android·flutter·ios
BG1 天前
Flutter 简仿Excel表格组件介绍
flutter
zhangmeng1 天前
FlutterBoost在iOS26真机运行崩溃问题
flutter·app·swift
恋猫de小郭1 天前
对于普通程序员来说 AI 是什么?AI 究竟用的是什么?
前端·flutter·ai编程
卡尔特斯1 天前
Flutter A GlobalKey was used multipletimes inside one widget'schild list.The ...
flutter
w_y_fan1 天前
Flutter 滚动组件总结
前端·flutter
醉过才知酒浓1 天前
Flutter Getx 的页面传参
flutter
火柴就是我2 天前
flutter 之真手势冲突处理
android·flutter