Flutter自定义iOS数字键盘插件sp_ios_num_keyboard的使用

Flutter自定义iOS数字键盘插件sp_ios_num_keyboard的使用

sp_ios_num_keyboard 是一个简单的数字键盘小部件。

pub package

安装

在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  sp_ios_num_keyboard: ^1.0.0

然后在你的 Dart 文件中导入该包:

import 'package:sp_ios_num_keyboard/sp_ios_num_keyboard.dart';

如何使用

创建一个 NumericKeyboard 小部件并传递所需的参数:

NumericKeyboard(
  onKeyboardTap: _onKeyboardTap,
)

其中 _onKeyboardTap 方法定义如下:

_onKeyboardTap(String value) {
  setState(() {
    text = text + value;
  });
}

参数

你可以通过传递额外的参数来自定义键盘的行为和外观:

NumericKeyboard(
  onKeyboardTap: _onKeyboardTap,
  textStyle: TextStyle(
    fontSize: 20.0,
    color: Colors.black
  ),
  rightButtonFn: () {
    if (text.isEmpty) return;
    setState(() {
      text = text.substring(0, text.length - 1);
    });
  },
  rightButtonLongPressFn: () {
    if (text.isEmpty) return;
    setState(() {
      text = '';
    });
  },
  rightIcon: Icon(Icons.backspace, color: Colors.red,),
  leftButtonFn: () {
    print('left button clicked');
  },
  leftIcon: Icon(Icons.check, color: Colors.red,),
  mainAxisAlignment: MainAxisAlignment.spaceEvenly
)

示例

这是一个完整的示例代码,展示了如何在 Flutter 应用中使用 sp_ios_num_keyboard 插件:

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

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SP iOS NUM KEYBOARD',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: const MyHomePage(title: 'On Screen Keyboard'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String text = "";

  onKeyboardTap(String value) {
    setState(() {
      text = text + value;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: InkWell(
          onTap: () {
            showDialog(
                context: context,
                builder: (BuildContext context) => Dialog(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12.0)),
                      child: NumericKeyboard(
                          onKeyboardTap: onKeyboardTap,
                          customTopWidget: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text("asdasd   "),
                            ],
                          ),
                          sizeNumButton: 40,
                          textStyle: const TextStyle(
                            color: Colors.black,
                            fontSize: 28,
                          ),
                          rightButtonFn: () {
                            if (text.isEmpty) return;
                            setState(() {
                              text = text.substring(0, text.length - 1);
                            });
                          },
                          rightButtonLongPressFn: () {
                            if (text.isEmpty) return;
                            setState(() {
                              text = text.substring(0, text.length - 1);
                            });
                          },
                          doneButtonFn: () => print("done"),
                          cancelButtonFn: () => print("cancel"),
                          textButtonStyle: TextStyle(color: Colors.blue),
                          textButtonPadding: EdgeInsets.all(10),
                          textButtonOnTopKeys: false,
                          rightIcon: const Stack(
                            children: [
                              Center(
                                child: Icon(
                                  Icons.backspace_outlined,
                                  color: Colors.grey,
                                  size: 27,
                                ),
                              ),
                            ],
                          ),
                          leftButtonFn: () {
                            if (text.isEmpty || text.contains(".")) return;
                            setState(() {
                              text = text + ".";
                            });
                          },
                          leftButtonLongPressFn: () {
                            if (text.isEmpty) return;
                            setState(() {
                              if (text.substring(0, 1) == '-') {
                                text = text.substring(1);
                              } else {
                                text = "-" + text;
                              }
                            });
                          },
                          leftIcon: const Stack(
                            children: [
                              Align(
                                child: Padding(
                                  padding: EdgeInsets.all(8.0),
                                  child: Text("-/+",
                                      style: TextStyle(
                                          color: Colors.grey, fontSize: 15)),
                                ),
                                alignment: Alignment.topRight,
                              ),
                              Center(
                                child: Text(".",
                                    style: TextStyle(
                                        color: Colors.black, fontSize: 30)),
                              ),
                            ],
                          ),
                          ),
                    ));
          },
          child: Text(widget.title,
              style: Theme.of(context).textTheme.headline6?.apply(
                  color: Colors.black,
                  fontSizeFactor: 2.3,
                  fontWeightDelta: 2)),
        ),
      ),
      body: SafeArea(
          child: Center(
              child: Column(children: [
        const Spacer(),
        Text(text,
            style: Theme.of(context).textTheme.headline6?.apply(
                color: Colors.black, fontSizeFactor: 2.3, fontWeightDelta: 2)),
        const Spacer(),
        NumericKeyboard(
            onKeyboardTap: onKeyboardTap,
            textStyle: const TextStyle(
              color: Colors.black,
              fontSize: 28,
            ),
            rightButtonFn: () {
              if (text.isEmpty) return;
              setState(() {
                text = text.substring(0, text.length - 1);
              });
            },
            rightButtonLongPressFn: () {
              if (text.isEmpty) return;
              setState(() {
                text = text.substring(0, text.length - 1);
              });
            },
            doneButtonFn: () => print("done"),
            cancelButtonFn: () => print("cancel"),
            textButtonStyle: TextStyle(color: Colors.blue),
            textButtonPadding: EdgeInsets.all(10),
            textButtonOnTopKeys: true,
            rightIcon: const Stack(
              children: [
                Center(
                  child: Icon(
                    Icons.backspace_outlined,
                    color: Colors.grey,
                    size: 27,
                  ),
                ),
              ],
            ),
            leftButtonFn: () {
              if (text.isEmpty || text.contains(".")) return;
              setState(() {
                text = text + ".";
              });
            },
            leftButtonLongPressFn: () {
              if (text.isEmpty) return;
              setState(() {
                if (text.substring(0, 1) == '-') {
                  text = text.substring(1);
                } else {
                  text = "-" + text;
                }
              });
            },
            leftIcon: const Stack(
              children: [
                Align(
                  child: Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text("-/+",
                        style: TextStyle(color: Colors.grey, fontSize: 15)),
                  ),
                  alignment: Alignment.topRight,
                ),
                Center(
                  child: Text(".",
                      style: TextStyle(color: Colors.black, fontSize: 30)),
                ),
              ],
            ),
            mainAxisAlignment: MainAxisAlignment.spaceBetween),
      ]))),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

更多关于Flutter自定义iOS数字键盘插件sp_ios_num_keyboard的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自定义iOS数字键盘插件sp_ios_num_keyboard的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用自定义iOS数字键盘插件sp_ios_num_keyboard的代码示例。为了使用此插件,首先确保你已经在pubspec.yaml文件中添加了依赖项,并运行了flutter pub get

1. 添加依赖项

在你的pubspec.yaml文件中添加以下依赖项:

dependencies:
  flutter:
    sdk: flutter
  sp_ios_num_keyboard: ^最新版本号 # 替换为插件的实际最新版本号

2. 导入插件并使用

接下来,在你的Flutter项目中导入并使用这个插件。以下是一个简单的示例,展示如何在你的应用中集成和使用sp_ios_num_keyboard

main.dart

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _controller = TextEditingController();
  String _inputText = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('自定义iOS数字键盘示例'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: '输入数字',
              ),
              keyboardType: TextInputType.number,
              inputFormatters: <TextInputFormatter>[
                FilteringTextInputFormatter.digitsOnly,
              ],
              onEditingComplete: () {
                // 当用户完成编辑时,获取输入文本
                setState(() {
                  _inputText = _controller.text;
                });
              },
              // 使用自定义键盘
              textInputAction: TextInputAction.done,
              onSubmitted: (String value) {
                // 处理提交事件
                print('提交的值: $value');
              },
            ),
            SizedBox(height: 20),
            // 自定义iOS数字键盘按钮
            ElevatedButton(
              onPressed: () {
                // 显示自定义键盘
                showCupertinoModalPopup<void>(
                  context: context,
                  builder: (BuildContext context) {
                    return CupertinoActionSheet(
                      title: Text('选择数字'),
                      message: Text('请选择一个数字'),
                      actions: <Widget>[
                        CupertinoActionSheetAction(
                          child: Text('1'),
                          onPressed: () {
                            Navigator.of(context).pop();
                            _controller.value = _controller.value.copyWith(
                              text: _controller.text + '1',
                              selection: TextSelection.fromPosition(
                                TextPosition(
                                  affinity: TextAffinity.downstream,
                                  offset: _controller.text.length + 1,
                                ),
                              ),
                              composing: TextRange.empty,
                            );
                          },
                        ),
                        CupertinoActionSheetAction(
                          child: Text('2'),
                          onPressed: () {
                            Navigator.of(context).pop();
                            _controller.value = _controller.value.copyWith(
                              text: _controller.text + '2',
                              selection: TextSelection.fromPosition(
                                TextPosition(
                                  affinity: TextAffinity.downstream,
                                  offset: _controller.text.length + 1,
                                ),
                              ),
                              composing: TextRange.empty,
                            );
                          },
                        ),
                        // 添加更多数字按钮...
                        // ...
                      ],
                      cancelButton: CupertinoActionSheetAction(
                        isDefaultAction: true,
                        child: Text('取消'),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                    );
                  },
                );
              },
              child: Text('显示自定义键盘'),
            ),
            SizedBox(height: 20),
            Text('输入的数字: $_inputText'),
          ],
        ),
      ),
    );
  }
}

注意:

  1. 实际插件使用:上述代码示例中并没有直接使用sp_ios_num_keyboard插件的API,因为该插件的具体API细节可能有所不同。通常,插件会有自己的文档和示例代码。你应该参考插件的README文件或官方文档来了解如何正确集成和使用。

  2. 自定义键盘实现:上述代码通过CupertinoActionSheet实现了一个自定义的数字选择界面,这可以作为使用自定义键盘的一个替代方案,尤其是在等待插件更新或具体实现细节时。

  3. 插件文档:确保查看sp_ios_num_keyboard插件的官方文档和示例代码,以获取最新的使用方法和最佳实践。

  4. iOS特定功能:由于插件名称中包含iOS,这意味着它可能专为iOS平台设计。在Android平台上使用时,可能需要额外的适配或替代方案。

请务必参考插件的官方文档和示例代码,以确保正确集成和使用。

回到顶部