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;