FocusDetector 是一个 Flutter 包,可检测小部件何时获得或失去焦点,使开发者能够实时响应可见性变化。它提供了小部件出现在屏幕上(获得焦点)或消失(失去焦点)时的回调,非常适合用于动画、跟踪用户交互或根据可见性管理状态。该包可在 Android、iOS、Web、macOS、Windows 和 Linux 等所有主要平台上运行,确保在不同目标环境中行为一致。它可轻松集成到现有的 Flutter 应用中,设置简单。
适合场景
用于分析的跟踪小部件可见性
出现时触发动画
基于焦点状态管理状态
通过暂停非活动小部件来优化性能
实现响应式 UI,使其对焦点变化做出反应
主要特点
实时焦点检测
跨平台兼容性
基于回调的简单 API
轻量且易于集成
支持焦点获取和丢失事件
适合对象
开发交互式 UI 的开发者
需要可见性感知逻辑的应用
由用户焦点触发的动画
对性能敏感的应用程序
需要生命周期感知的 Widgets
使用建议
需要正确的控件树结构
可能无法在复杂的嵌套布局中按预期工作
不适用于非交互式小部件
仅限聚焦相关事件
最好与有状态的部件或控制器一起使用
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
Focus Detector
Get notified every time your widget appears or disappears from the screen.
Similar to onResume()/onPause() on Android and viewDidAppear()/viewDidDisappear() on iOS.
Focus Detector fires callbacks for you whenever something happens to take or give your widget focus. Such an event might be, for instance, the user:
Navigating to/from another screen;
Turning the device’s screen on/off while your widget is visible;
Switching to/from another app while your widget is visible;
Scrolling your widget in/out the screen;
Usage
@overrideWidgetbuild(BuildContext context) =>
FocusDetector(
onFocusLost: () {
logger.i(
'Focus Lost.''\nTriggered when either [onVisibilityLost] or [onForegroundLost] ''is called.''\nEquivalent to onPause() on Android or viewDidDisappear() on iOS.',
);
},
onFocusGained: () {
logger.i(
'Focus Gained.''\nTriggered when either [onVisibilityGained] or [onForegroundGained] ''is called.''\nEquivalent to onResume() on Android or viewDidAppear() on iOS.',
);
},
onVisibilityLost: () {
logger.i(
'Visibility Lost.''\nIt means the widget is no longer visible within your app.',
);
},
onVisibilityGained: () {
logger.i(
'Visibility Gained.''\nIt means the widget is now visible within your app.',
);
},
onForegroundLost: () {
logger.i(
'Foreground Lost.''\nIt means, for example, that the user sent your app to the background by opening ''another app or turned off the device\'s screen while your ''widget was visible.',
);
},
onForegroundGained: () {
logger.i(
'Foreground Gained.''\nIt means, for example, that the user switched back to your app or turned the ''device\'s screen back on while your widget was visible.',
);
},
child: Container(),
);
Usage Scenarios
Turn on and off resource-consuming features, such as camera, location or bluetooth;
Sync your data with a remote API or local database;
Pause and resume video/audio playback or streaming;