custom_keyboard.md 2.4 KB
Newer Older
Kevin's avatar
Kevin committed
1 2
# 自定义键盘使用方法快速入门

Kevin's avatar
Kevin committed
3 4 5 6
## 效果

<img width="38%" height="38%" src="./images/custom_keyboard.gif"/>

Kevin's avatar
Kevin committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
## Step1
编写个性化的键盘

```dart
class NumberKeyboard extends StatelessWidget{
    static const CKTextInputType inputType = const CKTextInputType(name:'CKNumberKeyboard'); //定义InputType类型
    static double getHeight(BuildContext ctx){ //编写获取高度的方法
         ...
    }


  final KeyboardController controller ; //用于控制键盘输出的Controller
  const NumberKeyboard({this.controller});

   static register(){   //注册键盘的方法
      CoolKeyboard.addKeyboard(NumberKeyboard.inputType,KeyboardConfig(builder: (context,controller){
        return NumberKeyboard(controller: controller);
      },getHeight: NumberKeyboard.getHeight));
    }

    @override
    Widget build(BuildContext context) { //键盘的具体内容
      ...
      return Container( //例子
        color: Colors.white,
        child: GestureDetector(
           behavior: HitTestBehavior.translucent,
           child: Center(child: Text('1'),),
           onTap: (){
              controller.addText('1'); 往输入框光标位置添加一个1
           },
        ),
      )
    }
}
```

## Step2
Kevin's avatar
Kevin committed
45
注册键盘,并且添加了KeyboardRootWidget
Kevin's avatar
Kevin committed
46 47 48 49

```dart
void main(){
  NumberKeyboard.register(); //注册键盘
Kevin's avatar
Kevin committed
50
  runApp(KeyboardRootWidget(child: MyApp())); //添加了KeyboardRootWidget
Kevin's avatar
Kevin committed
51 52 53 54 55 56 57 58 59 60
}
```

## Step3
给需要使用自定义键盘的页面添加以下代码

```dart
@override
Widget build(BuildContext context) {
  return KeyboardMediaQuery(//用于键盘弹出的时候页面可以滚动到输入框的位置
Kevin's avatar
Kevin committed
61
      child: Page
Kevin's avatar
Kevin committed
62 63 64 65 66 67 68 69 70 71
  );
}
```


## Step4
具体使用
```dart
TextField(
   ...
Kevin's avatar
Kevin committed
72
   keyboardType: NumberKeyboard.inputType, 像平常一样设置键盘输入类型一样将Step1编写的inputType传递进去
Kevin's avatar
Kevin committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
   ...
 )
```

# KeyboardController


- [deleteOne](#deleteOne)
- [addText](#addText)
- [doneAction](#doneAction)
- [nextAction](#nextAction)
- [sendPerformAction](#sendPerformAction)


### deleteOne()
删除一个字符,一般用于键盘的删除键

### addText(String insertText)
在光标位置添加文字,一般用于键盘输入

### doneAction()
触发键盘的完成Action

### nextAction()
触发键盘的下一项Action

### newLineAction()
触发键盘的换行Action

### sendPerformAction(TextInputAction action)
///发送其他Action