Flutter键盘可见性检测插件flutter_keyboard_visibility的使用

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

Flutter键盘可见性检测插件flutter_keyboard_visibility的使用

Flutter 开发中,有时需要根据键盘的显示状态来调整界面布局或执行特定操作。flutter_keyboard_visibility 插件可以帮助开发者轻松实现这一需求。

安装

在您的 pubspec.yaml 文件中添加依赖:

dependencies:
  flutter_keyboard_visibility: ^latest_version # 请替换为最新版本号

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

使用方法

1. 在Widget树中使用Builder

通过 KeyboardVisibilityBuilder 可以根据键盘是否可见来构建不同的 UI。

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

class KeyboardVisibilityDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Keyboard Visibility Demo')),
      body: Center(
        child: KeyboardVisibilityBuilder(
          builder: (context, isKeyboardVisible) {
            return Text(
              'The keyboard is: ${isKeyboardVisible ? 'VISIBLE' : 'NOT VISIBLE'}',
              style: TextStyle(fontSize: 24),
            );
          },
        ),
      ),
    );
  }
}

2. 使用Provider模式

KeyboardVisibilityProvider 放置在应用较高层级,并在其子组件中读取键盘状态。

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

class ProviderDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 放置在较高级别
    return KeyboardVisibilityProvider(
      child: Scaffold(
        appBar: AppBar(title: Text('Provider Demo')),
        body: Center(
          child: Builder(builder: (BuildContext context) {
            final bool isKeyboardVisible =
                KeyboardVisibilityProvider.isKeyboardVisible(context);
            return Text(
              'The keyboard is: ${isKeyboardVisible ? 'VISIBLE' : 'NOT VISIBLE'}',
              style: TextStyle(fontSize: 24),
            );
          }),
        ),
      ),
    );
  }
}

3. 直接查询与订阅

利用 KeyboardVisibilityController 类直接查询当前键盘状态或订阅其变化事件。

import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'dart:async';

class DirectQueryAndSubscriptionDemo extends StatefulWidget {
  @override
  _DirectQueryAndSubscriptionDemoState createState() =>
      _DirectQueryAndSubscriptionDemoState();
}

class _DirectQueryAndSubscriptionDemoState
    extends State<DirectQueryAndSubscriptionDemo> {
  late StreamSubscription<bool> keyboardSubscription;

  @override
  void initState() {
    super.initState();

    var keyboardVisibilityController = KeyboardVisibilityController();
    print('Keyboard visibility direct query: ${keyboardVisibilityController.isVisible}');

    keyboardSubscription = keyboardVisibilityController.onChange.listen((bool visible) {
      print('Keyboard visibility update. Is visible: $visible');
      setState(() {});
    });
  }

  @override
  void dispose() {
    keyboardSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Direct Query & Subscription Demo')),
      body: Center(
        child: Text(
          'Check logs for keyboard visibility updates.',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

4. 点击空白处收起键盘

使用 KeyboardDismissOnTap 组件包裹整个页面,当用户点击非输入框区域时自动收起键盘。

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

class KeyboardDismissDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      child: Scaffold(
        appBar: AppBar(title: Text('Keyboard Dismiss On Tap Demo')),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              TextField(decoration: InputDecoration(labelText: 'Input Box')),
              Spacer(),
              ElevatedButton(onPressed: () {}, child: Text('Submit'))
            ],
          ),
        ),
      ),
    );
  }
}

以上就是 flutter_keyboard_visibility 插件的基本用法示例,希望能帮助到您!如果您有任何问题或需要进一步的帮助,请随时提问。


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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_keyboard_visibility插件来检测键盘可见性的详细代码示例。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_keyboard_visibility: ^5.0.0  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

2. 导入插件

在你需要使用键盘可见性检测的Dart文件中导入插件:

import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';

3. 使用插件

下面是一个简单的示例,展示如何在Flutter应用中检测键盘的可见性并更新UI。

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: KeyboardVisibilityExample(),
    );
  }
}

class KeyboardVisibilityExample extends StatefulWidget {
  @override
  _KeyboardVisibilityExampleState createState() => _KeyboardVisibilityExampleState();
}

class _KeyboardVisibilityExampleState extends State<KeyboardVisibilityExample> with WidgetsBindingObserver {
  bool _isKeyboardVisible = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
    
    // 监听键盘可见性变化
    KeyboardVisibility.addChangeListener(
      onChange: (visibility) {
        setState(() {
          _isKeyboardVisible = visibility;
        });
      }
    );
  }

  @override
  void dispose() {
    // 移除监听器
    KeyboardVisibility.removeChangeListener(null);
    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Keyboard Visibility Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Keyboard is ${_isKeyboardVisible ? "visible" : "not visible"}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            TextField(
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Type something...',
              ),
            ),
          ],
        ),
      ),
    );
  }
}

解释

  1. 添加依赖:在pubspec.yaml文件中添加flutter_keyboard_visibility插件。
  2. 导入插件:在需要使用插件的Dart文件中导入flutter_keyboard_visibility
  3. 初始化监听器:在initState方法中,添加KeyboardVisibility的监听器,当键盘可见性变化时更新状态。
  4. 移除监听器:在dispose方法中移除监听器,以避免内存泄漏。
  5. UI更新:根据键盘的可见性更新UI文本。

这个示例展示了如何在Flutter应用中检测键盘的可见性并相应地更新UI。你可以根据需要在你的应用中扩展这一功能。

回到顶部