简体   繁体   中英

Keyboard dismissing when setState is called

I want to hide/show some widgets in a Scaffold when a TextFormField has focus or not.

I've managed to do it by wrapping the TextField in a Focus widget but whenever I tap it to start typing the widgets I'm trying to hide disappear but the Keyboard loses focus until I tap the TextField a second time.

Any ideas why this is happening and how to prevent it?

You can use flutter_keyboard_visibility package:

There are several ways to build your Widget tree with it, like use separate of boolean:

    // Add new variable for keyboard in your Stateful widget
    bool keyboardIsVisible = false;

    // Add listener at initState
      @override
      void initState() {
        super.initState();

        KeyboardVisibilityNotification().addNewListener(
          onChange: (bool visible) {
          keyboardIsVisible = visible;
          setState(() {});
      },
    );
  }

Or you can use thier builder widget:

    import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';

/// In any of your widgets...
@override
Widget build(BuildContext context) {
  return KeyboardVisibilityBuilder(
    builder: (context, isKeyboardVisible) {
      return Text(
        'The keyboard is: ${isKeyboardVisible ? 'VISIBLE' : 'NOT VISIBLE'}',
      );
    }
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM