Flutter custom keyboard solution

Preface:

Flutter currently has no official solution for custom keyboards, but we need to use them sometimes, such as money keyboards, secure password keyboards, and various custom quick input keyboards Therefore, I wrote a plug-in to customize the keyboard. Since it is implemented by intercepting PlatformChannel, it can seamlessly connect TextFiled and other input boxes GitHub links that come with Flutter

The effect

Usage:

Install dependencies

Dependencies: cool_ui: "^ 0.1.14"Copy the code

Import packages

import 'package:cool_ui/cool_ui.dart';
Copy the code

Write a custom keyboard Widget

class NumberKeyboard extends StatelessWidget{
    static const CKTextInputType inputType = const CKTextInputType(name:'CKNumberKeyboard'); // Define the InputType type
    static double getHeight(BuildContext ctx){ // Write the method to get the height. }final KeyboardController controller ; // The Controller used to control the keyboard output
    const NumberKeyboard({this.controller});

    static register(){   // Register the keyboard method
        CoolKeyboard.addKeyboard(NumberKeyboard.inputType,KeyboardConfig(builder: (context,controller){
            return NumberKeyboard(controller: controller);
        },getHeight: NumberKeyboard.getHeight));
    }

    @override
    Widget build(BuildContext context) { // The contents of the keyboard.return Container( / / case
        color: Colors.white,
        child: GestureDetector(
           behavior: HitTestBehavior.translucent,
           child: Center(child: Text('1'),),
           onTap: (){
              controller.addText('1'); Add one to the input field cursor position1},),)}}Copy the code

Register the keyboard

void main(){
  NumberKeyboard.register(); // Register the keyboard
  runApp(MyApp());
}
Copy the code

Using the keyboard

First modify the following code in the page where you need to use the keyboard

@override
Widget build(BuildContext context) {
  return KeyboardMediaQuery(// Used to scroll to the input box when the keyboard pops up
      child: Builder(builder: (ctx) {
        CoolKeyboard.init(ctx); // Initialize the keyboard listener and pass the current page context
        return Page; // Return to the current page})); }Copy the code

Then set the keyboardType of the TextField to the type of your custom keyboard

TextField(
   ...
   keyboardType: NumberKeyboard.inputType
   ...
 )
Copy the code