Flutter键盘管理插件flutter_keyboard的使用

Flutter键盘管理插件flutter_keyboard的使用

本文档介绍了如何使用flutter_keyboard插件来管理Flutter应用中的键盘行为。通过使用此插件,您可以轻松避免键盘遮挡输入框的问题。


特性

  • 自动滚动到被键盘遮挡的输入框(如TextField)。
  • 支持自动调整布局以适应键盘的出现和消失。
  • 简单易用,无需手动处理复杂的键盘事件逻辑。

安装步骤

  1. 在项目的pubspec.yaml文件中添加依赖:

    dependencies:
      flutter_keyboard: ^版本号
    
  2. 运行以下命令安装依赖:

    flutter pub get
    

使用方法

基本使用示例

首先,确保在你的项目中导入了flutter_keyboard包:

import 'package:flutter_keyboard/flutter_keyboard.dart';

然后,将KeyboardAvoiderPkg包裹在需要管理键盘的容器周围即可。例如:

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      resizeToAvoidBottomInset: true, // 可选:启用自动调整底部内边距
      body: KeyboardAvoiderPkg( // 包裹键盘管理器
        autoScroll: true, // 是否自动滚动到焦点输入框
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/Register.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: Container(
            height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
              color: Colors.black54,
            ),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  SizedBox(height: 55), // 空白间距
                  Stack(
                    children: [
                      CircleAvatar(
                        radius: 80.0,
                        backgroundColor: Colors.white12,
                        child: Icon(
                          Icons.supervised_user_circle_outlined,
                          size: 45,
                          color: Colors.white,
                        ),
                      ),
                      Positioned(
                        top: 120,
                        left: 110,
                        child: CircleIconButton(
                          icon: Icon(
                            Icons.arrow_upward_rounded,
                            size: 18,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 110), // 空白间距
                  TextInputOpacity(
                    icon: Icon(
                      Icons.supervised_user_circle_outlined,
                      color: Colors.white,
                    ),
                    title: 'Nom(s)', // 名字
                  ),
                  SizedBox(height: 20), // 空白间距
                  TextInputOpacity(
                    icon: Icon(
                      Icons.supervised_user_circle_outlined,
                      color: Colors.white,
                    ),
                    title: 'Prénom(s)', // 姓氏
                  ),
                  SizedBox(height: 20), // 空白间距
                  TextInputOpacity(
                    icon: Icon(
                      Icons.mail,
                      color: Colors.white,
                    ),
                    title: 'Email', // 邮箱
                  ),
                  SizedBox(height: 20), // 空白间距
                  TextInputOpacity(
                    icon: Icon(
                      Icons.lock,
                      color: Colors.white,
                    ),
                    title: 'Password', // 密码
                  ),
                  SizedBox(height: 20), // 空白间距
                  TextInputOpacity(
                    icon: Icon(
                      Icons.lock,
                      color: Colors.white,
                    ),
                    title: 'Confirm Password', // 确认密码
                  ),
                  SizedBox(height: 55), // 空白间距
                  BigBlueButton(
                    title: 'Enregistrer', // 注册按钮
                    onPress: () {
                      print('Okay, we can send the data'); // 模拟数据提交
                    },
                  ),
                  SizedBox(height: 55), // 空白间距
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        'Vous avez déjà un compte?', // 已有账户?
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 15,
                        ),
                      ),
                      TextSimpleButton(
                        title: 'Login', // 登录
                        colors: Colors.blue,
                        onPress: () {
                          Navigator.pop(context); // 返回上一页
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class CircleIconButton extends StatelessWidget {
  const CircleIconButton({
    Key? key,
    this.icon,
    this.onPress,
  }) : super(key: key);

  final Icon? icon;
  final Function? onPress;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Container(
      width: 35,
      height: 35,
      decoration: BoxDecoration(
        color: Colors.blue,
        shape: BoxShape.circle,
        border: Border.all(
          color: Colors.white,
        ),
      ),
      child: IconButton(
        icon: icon ?? Icon(Icons.ac_unit),
        onPressed: () {
          (onPress ?? () {})(); // 执行点击回调
        },
      ),
    );
  }
}

更多关于Flutter键盘管理插件flutter_keyboard的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


flutter_keyboard 是一个用于管理 Flutter 应用中键盘行为的插件。它可以帮助你监听键盘的显示和隐藏事件,以及获取键盘的高度等信息。以下是如何使用 flutter_keyboard 插件的基本步骤:

1. 添加依赖

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

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

然后运行 flutter pub get 来获取依赖。

2. 导入包

在你的 Dart 文件中导入 flutter_keyboard 包:

import 'package:flutter_keyboard/flutter_keyboard.dart';

3. 使用 Keyboard

flutter_keyboard 提供了 Keyboard 类来管理键盘的行为。你可以使用它来监听键盘的显示和隐藏事件,以及获取键盘的高度。

监听键盘的显示和隐藏

你可以使用 Keyboard.addListener 来监听键盘的显示和隐藏事件:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double _keyboardHeight = 0.0;
  bool _isKeyboardVisible = false;

  @override
  void initState() {
    super.initState();
    Keyboard.addListener(_onKeyboardChange);
  }

  @override
  void dispose() {
    Keyboard.removeListener(_onKeyboardChange);
    super.dispose();
  }

  void _onKeyboardChange() {
    setState(() {
      _keyboardHeight = Keyboard.height;
      _isKeyboardVisible = Keyboard.isVisible;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Keyboard Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Keyboard Height: $_keyboardHeight'),
            Text('Keyboard Visible: $_isKeyboardVisible'),
          ],
        ),
      ),
    );
  }
}

获取键盘高度

你可以通过 Keyboard.height 来获取当前键盘的高度:

double keyboardHeight = Keyboard.height;

检查键盘是否可见

你可以通过 Keyboard.isVisible 来检查键盘是否可见:

bool isKeyboardVisible = Keyboard.isVisible;

4. 处理键盘事件

你可以在 _onKeyboardChange 方法中处理键盘的显示和隐藏事件,例如调整 UI 布局或执行其他操作。

5. 移除监听器

dispose 方法中,记得移除监听器以避免内存泄漏:

@override
void dispose() {
  Keyboard.removeListener(_onKeyboardChange);
  super.dispose();
}

6. 其他功能

flutter_keyboard 还提供了其他一些功能,例如手动显示或隐藏键盘:

Keyboard.show();  // 显示键盘
Keyboard.hide();  // 隐藏键盘
回到顶部