flutter_persistent_keyboard_height Pub版本

Flutter 包,用于获取键盘高度。高度会在应用会话和键盘状态之间持久化(您可以在键盘关闭时使用该高度)。

用法

注册提供程序

您需要做的第一件事是将您想获取键盘高度的子 widget 包裹在 PersistentKeyboardHeightProvider 中。如果您想从所有 widget 获取键盘高度,请将其添加到您的应用 widget(可能是 MaterialApp)的 builder 中。

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!,
      ),
    );
  }
}

获取键盘高度

要获取键盘高度,请使用 PersistentKeyboardHeight 继承 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'),
      ],
    ),
  );
}

使用自定义存储提供程序

默认情况下,该包使用 shared_preferences 来保存键盘高度,但如果您想使用自定义解决方案来保存高度,可以通过实现 IPersistentKeyboardHeightStorageProvider 接口并将类的实例传递给 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!,
      ),
    );
  }
}

开发过程

这个包的第一个版本是在两次直播中开发的。不幸的是,我第一次直播时声音消失了,但第二次直播是正常的。如果您想观看,链接如下: 第一部分第二部分

鸣谢

GitHub

查看 Github