Flutter焦点检测插件pb_focus_detector的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter焦点检测插件pb_focus_detector的使用

Focus Detector Logo

Pub.dev Badge GitHub Build Badge Gitter Badge Effective Dart Badge MIT License Badge Flutter Platform Badge

Focus Detector

获取每次您的小部件从屏幕上出现或消失时的通知。

类似于Android中的onResume()/onPause()和iOS中的viewDidAppear()/viewDidDisappear()

Focus Detector会在您的小部件获得或失去焦点时触发回调。例如:

  • 用户导航到其他屏幕;
  • 关闭设备屏幕时您的小部件仍然可见;
  • 切换到其他应用时您的小部件仍然可见;
  • 滚动导致您的小部件进入或离开屏幕。

使用方法

以下是pb_focus_detector的基本用法示例:

[@override](/user/override)
Widget build(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(), // 小部件的子节点
    );

使用场景

以下是一些常见的使用场景:

  1. 资源控制
    在小部件失去焦点时关闭高耗能功能(如相机、位置服务、蓝牙等),在获得焦点时重新启用。

  2. 数据同步
    在小部件获得焦点时与远程API或本地数据库同步数据。

  3. 媒体播放控制
    暂停和恢复视频或音频的播放。


完整示例代码

以下是一个完整的示例,展示了如何使用pb_focus_detector来检测小部件的焦点变化。

示例代码

import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:pb_focus_detector/pb_focus_detector.dart';

class FocusDetectorExample extends StatelessWidget {
  [@override](/user/override)
  Widget build(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: Material(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  '发送应用到后台或推送另一个页面并观察控制台输出。',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 20,
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                ElevatedButton(
                  onPressed: () {
                    final route = MaterialPageRoute(
                      builder: (_) => OtherPage(),
                    );
                    Navigator.of(context).push(route);
                  },
                  child: const Text(
                    '推送另一个页面',
                  ),
                )
              ],
            ),
          ),
        ),
      );
}

class OtherPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(),
        body: const Padding(
          padding: EdgeInsets.all(16),
          child: Center(
            child: Text(
              '查看控制台并返回第一个页面。',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ),
        ),
      );
}

Logger logger = Logger(
  printer: PrettyPrinter(
    methodCount: 0,
    printTime: false,
  ),
);

void main() {
  runApp(
    MaterialApp(
      home: FocusDetectorExample(),
      theme: ThemeData(),
    ),
  );
}

更多关于Flutter焦点检测插件pb_focus_detector的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter焦点检测插件pb_focus_detector的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


pb_focus_detector 是一个用于检测 Flutter 应用中 Widget 焦点变化的插件。它可以帮助你监听某个 Widget 是否获得了焦点或失去了焦点,从而执行相应的操作。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 pb_focus_detector 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  pb_focus_detector: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装插件。

使用 pb_focus_detector

pb_focus_detector 提供了一个 FocusDetector Widget,你可以将它包裹在你想要监听焦点变化的 Widget 外面。

基本用法

import 'package:flutter/material.dart';
import 'package:pb_focus_detector/pb_focus_detector.dart';

class MyHomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Focus Detector Example'),
      ),
      body: Center(
        child: FocusDetector(
          onFocusGained: () {
            print('Widget gained focus');
          },
          onFocusLost: () {
            print('Widget lost focus');
          },
          child: Container(
            width: 200,
            height: 200,
            color: Colors.blue,
            child: Center(
              child: Text(
                'Focus Me',
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!