0

I wrote code for custom keyboard in Scaffold and set keyboardType: TextInputType.none to close the default keyboard. The code is working but opposite to expected behavior. When I am focusing on TextField Keyboard disappears and when I am out of focus Keyboard appears. Why is this happening. What is the bug in the code?

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: KeyboardDemo(),
    );
  }
}

class KeyboardDemo extends StatefulWidget {
  const KeyboardDemo({Key? key}) : super(key: key);

  @override
  _KeyboardDemoState createState() => _KeyboardDemoState();
}

class _KeyboardDemoState extends State<KeyboardDemo> {
  final TextEditingController _controller = TextEditingController();
  late FocusNode _focus;

  @override
  void initState() {
    super.initState();
    _focus.addListener(_onFocusChange);
  }


  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
    _focus.removeListener(_onFocusChange);
    _focus.dispose();
  }

  void _onFocusChange() {
    debugPrint("Focus: ${_focus.hasFocus.toString()}");
  }

  void buildBottomSheet() {
    showModalBottomSheet(
        barrierColor: Colors.transparent,
        builder: (BuildContext context) {
          return CustomKeyboard(
            onTextInput: (myText) {
              _insertText(myText);
            },
            onBackspace: () {
              _backspace();
            },
          );
        },
        context: context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Column(
        children: [
          const SizedBox(height: 50),
          Container(
            color: Colors.amber,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                controller: _controller,
                keyboardType: TextInputType.none,
                focusNode: _focus,
                onTap: () {
                  debugPrint(
                      "Focus in bottom Sheet: ${_focus.hasFocus.toString()}");
                  buildBottomSheet();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

enter image description here enter image description here

  • There are some error in defining `late FocusNode _focus;`. In `initState`, `_focus.addListener(_onFocusChange);` should call on `null` – Sam Chan Feb 10 '22 at 06:55
  • @SamChan There is no difference in changing the condition. Thanks for the suggestion. `The operand can't be null, so the condition is always false. Try removing the condition, an enclosing condition, or the whole conditional statement `. – Chaitanya Dokara Feb 10 '22 at 09:22

0 Answers0