Flutter键盘高度监听插件flutter_persistent_keyboard_height的使用

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

Flutter键盘高度监听插件flutter_persistent_keyboard_height的使用

flutter_persistent_keyboard_height Pub version

Flutter package to get keyboard height. The height is persisted during app sessions and keyboard states (you can use the height when keyboard is closed).

Usage

Registering the provider

First thing you need to do is wrap a widget from children of which you want to get the keyboard height with PersistentKeyboardHeightProvider. Add it to the builder of your app widget (perhaps MaterialApp) if you want to get keyboard height from all widgets.

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Persistent Keyboard Height Example',
      home: const FlutterPersistentKeyboardHeightExample(),
      builder: (context, child) => PersistentKeyboardHeightProvider(
        child: child!,
      ),
    );
  }
}

Getting the keyboard height

In order to get keyboard height use the PersistentKeyboardHeight inherited widget:

Widget build(BuildContext context) {
  final keyboardHeight = PersistentKeyboardHeight.of(context).keyboardHeight;

  return Scaffold(
    body: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Padding(
          padding: EdgeInsets.all(16.0),
          child: TextField(
            decoration: InputDecoration(
              labelText: 'Flutter Persistent Keyboard Size Example',
            ),
          ),
        ),
        const SizedBox(height: 8),
        Text('Keyboard height: $keyboardHeight'),
      ],
    ),
  );
}

Using a custom storage provider

By default, the package uses shared_preferences to preserve the keyboard height but if you want to use a custom solution for preserving the height you can do that by implementing the IPersistentKeyboardHeightStorageProvider interface and passing an instance of the class to PersistentKeyboardHeightProvider:

class CustomPersistentKeyboardHeightStorageProvider implements IPersistentKeyboardHeightStorageProvider {
  const CustomPersistentKeyboardHeightStorageProvider();

  @override
  Future<double> getHeight() {
    // read the height from storage
  }

  @override
  Future<void> setHeight(double height) {
    // save the height to storage
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Persistent Keyboard Height Example',
      home: const FlutterPersistentKeyboardHeightExample(),
      builder: (context, child) => PersistentKeyboardHeightProvider(
        child: child!,
      ),
    );
  }
}

Complete Demo

Here is a complete demo showing how to use flutter_persistent_keyboard_height in a Flutter application.

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Persistent Keyboard Height Example',
      home: const FlutterPersistentKeyboardHeightExample(),
      builder: (context, child) => PersistentKeyboardHeightProvider(
        child: child!,
      ),
    );
  }
}

class FlutterPersistentKeyboardHeightExample extends StatelessWidget {
  const FlutterPersistentKeyboardHeightExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final keyboardHeight = PersistentKeyboardHeight.of(context).keyboardHeight;

    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Padding(
            padding: EdgeInsets.all(16.0),
            child: TextField(
              decoration: InputDecoration(
                labelText: 'Flutter Persistent Keyboard Size Example',
              ),
            ),
          ),
          const SizedBox(height: 8),
          Text('Keyboard height: $keyboardHeight'),
        ],
      ),
    );
  }
}

This demo sets up a simple Flutter app that displays the current keyboard height whenever the keyboard is open or closed. It wraps the entire app with PersistentKeyboardHeightProvider to ensure that any part of the app can access the keyboard height using PersistentKeyboardHeight.of(context).keyboardHeight.

For more information on the development process and acknowledgments, please refer to the original documentation.


更多关于Flutter键盘高度监听插件flutter_persistent_keyboard_height的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter键盘高度监听插件flutter_persistent_keyboard_height的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_persistent_keyboard_height插件来监听键盘高度的示例代码。这个插件可以帮助你在键盘弹出和隐藏时获取其高度,以便进行相应的UI调整。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_persistent_keyboard_height: ^x.y.z  # 请替换为最新版本号

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

2. 导入插件

在你的Dart文件中导入插件:

import 'package:flutter_persistent_keyboard_height/flutter_persistent_keyboard_height.dart';

3. 使用插件

下面是一个完整的示例,展示如何监听键盘高度的变化并更新UI:

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

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

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

class KeyboardHeightListenerExample extends StatefulWidget {
  @override
  _KeyboardHeightListenerExampleState createState() => _KeyboardHeightListenerExampleState();
}

class _KeyboardHeightListenerExampleState extends State<KeyboardHeightListenerExample> with WidgetsBindingObserver {
  double _keyboardHeight = 0.0;
  bool _isKeyboardVisible = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addObserver(this);
    // 初始化监听器
    KeyboardHeightController.init().addListener(_onKeyboardHeightChanged);
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance?.removeObserver(this);
    // 移除监听器
    KeyboardHeightController.instance?.removeListener(_onKeyboardHeightChanged);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 监听应用生命周期状态变化,这里可以添加额外的逻辑
  }

  void _onKeyboardHeightChanged() {
    double keyboardHeight = KeyboardHeightController.instance?.keyboardHeight ?? 0.0;
    bool isVisible = keyboardHeight > 0.0;

    if (_keyboardHeight != keyboardHeight || _isKeyboardVisible != isVisible) {
      setState(() {
        _keyboardHeight = keyboardHeight;
        _isKeyboardVisible = isVisible;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Keyboard Height Listener Example'),
      ),
      body: Padding(
        padding: EdgeInsets.only(bottom: _keyboardHeight),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              decoration: InputDecoration(labelText: 'Type something...'),
            ),
            SizedBox(height: 20),
            Text(
              'Keyboard Height: ${_keyboardHeight.toStringAsFixed(2)}',
              style: TextStyle(fontSize: 18),
            ),
            Text(
              'Is Keyboard Visible: $_isKeyboardVisible',
              style: TextStyle(fontSize: 18),
            ),
          ],
        ),
      ),
    );
  }
}

解释

  1. 依赖添加:在pubspec.yaml文件中添加flutter_persistent_keyboard_height依赖。
  2. 导入插件:在需要使用插件的Dart文件中导入它。
  3. 初始化监听器:在initState方法中初始化键盘高度监听器,并在dispose方法中移除监听器。
  4. 监听回调:在_onKeyboardHeightChanged方法中处理键盘高度变化,并更新UI状态。
  5. UI更新:在build方法中根据键盘高度和可见性状态更新UI,例如调整Padding和显示当前键盘高度及可见性状态。

这个示例展示了如何使用flutter_persistent_keyboard_height插件来监听键盘高度的变化,并据此更新UI。你可以根据自己的需求进一步定制和扩展这个示例。

回到顶部