GithubHelp home page GithubHelp logo

misterjimson / flutter_keyboard_visibility Goto Github PK

View Code? Open in Web Editor NEW
394.0 7.0 107.0 431 KB

Get notified on keyboard visibility changes in your Flutter app

License: MIT License

Dart 39.99% Java 3.17% Ruby 2.96% Objective-C 3.86% Shell 1.04% HTML 1.69% Kotlin 0.18% CMake 21.11% C++ 23.56% C 1.60% Swift 0.85%

flutter_keyboard_visibility's Introduction

Flutter Keyboard Visibility

pub package ci codecov

React to keyboard visibility changes.

Note about Flutter Web and Desktop support

Web support is an open issue here, desktop support is an open issue here. Currently this library will just return false for keyboard visibility on web and desktop.

Install

Install the package

Usage: React to Keyboard Visibility Changes

Option 1: Within your Widget tree using a builder

Build your Widget tree based on whether or not the keyboard is visible by using KeyboardVisibilityBuilder.

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'}',
        );
      }
  );

Option 2: Within your Widget tree using a provider

Build your Widget tree based on whether or not the keyboard is visible by including a KeyboardVisibilityProvider near the top of your tree.

import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';

// Somewhere near the top of your tree...
@override
Widget build(BuildContext context) {
  return KeyboardVisibilityProvider(
    child: MyDemoPage(),
  );
}

// Within MyDemoPage...
@override
Widget build(BuildContext context) {
  final bool isKeyboardVisible = KeyboardVisibilityProvider.isKeyboardVisible(context);
  return Text(
    'The keyboard is: ${isKeyboardVisible ? 'VISIBLE' : 'NOT VISIBLE'}',
  );
}

Option 3: Direct query and subscription

Query and/or subscribe to keyboard visibility directly with the KeyboardVisibilityController class.

import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'dart:async';

late StreamSubscription<bool> keyboardSubscription;

@override
void initState() {
  super.initState();

  var keyboardVisibilityController = KeyboardVisibilityController();
  // Query
  print('Keyboard visibility direct query: ${keyboardVisibilityController.isVisible}');

  // Subscribe
  keyboardSubscription = keyboardVisibilityController.onChange.listen((bool visible) {
    print('Keyboard visibility update. Is visible: $visible');
  });
}

@override
void dispose() {
  keyboardSubscription.cancel();
  super.dispose();
}

Usage: Dismiss keyboard on tap

Place a KeyboardDismissOnTap near the top of your Widget tree. When a user taps outside of the currently focused Widget, the Widget will drop focus and the keyboard will be dismissed.

import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';

// Somewhere near the top of your tree...
@override
Widget build(BuildContext context) {
  return KeyboardDismissOnTap(
    child: MyDemoPage(),
  );
}

By default KeyboardDismissOnTap will only dismiss taps not captured by other interactive Widgets, like buttons. If you would like to dismiss the keyboard for any tap, including taps on interactive Widgets, set dismissOnCapturedTaps to true.

import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';

// Somewhere near the top of your tree...
@override
Widget build(BuildContext context) {
  return KeyboardDismissOnTap(
    dismissOnCapturedTaps: true,
    child: MyDemoPage(),
  );
}

The IgnoreKeyboardDismiss Widget can be used to further refine which taps do and do not dismiss the keyboard. Checkout the example app for more detail.

Testing

Testing using mocks

KeyboardVisibilityProvider and KeyboardVisibilityBuilder accept a controller parameter that allow you to mock or replace the logic for reporting keyboard visibility updates.

@GenerateMocks([KeyboardVisibilityController])
void main() {
  testWidgets('It reports true when the keyboard is visible', (WidgetTester tester) async {
    // Pretend that the keyboard is visible.
    var mockController = MockKeyboardVisibilityController();
    when(mockController.onChange)
        .thenAnswer((_) => Stream.fromIterable([true]));
    when(mockController.isVisible).thenAnswer((_) => true);

    // Build a Widget tree and query KeyboardVisibilityProvider
    // for the visibility of the keyboard.
    bool? isKeyboardVisible;

    await tester.pumpWidget(
      KeyboardVisibilityProvider(
        controller: mockController,
        child: Builder(
          builder: (BuildContext context) {
            isKeyboardVisible =
                KeyboardVisibilityProvider.isKeyboardVisible(context);
            return SizedBox();
          },
        ),
      ),
    );

    // Verify that KeyboardVisibilityProvider reported that the
    // keyboard is visible.
    expect(isKeyboardVisible, true);
  });
}

Testing with a global override

Call KeyboardVisibilityTesting.setVisibilityForTesting(false); to set a custom value to use during flutter test. This is set globally and will override the standard logic of the native platform.

void main() {
  testWidgets('My Test', (WidgetTester tester) async {
    KeyboardVisibilityTesting.setVisibilityForTesting(true);
    await tester.pumpWidget(MyApp());
  });
}

flutter_keyboard_visibility's People

Contributors

adee42 avatar andrflor avatar askarsyzdykov avatar cbenhagen avatar davidmartos96 avatar esteveaguilera avatar hmayer00 avatar jamieastley avatar jpeiffer avatar lukepighetti avatar matthew-carroll avatar misterjimson avatar pin73 avatar vinceramcesoliveros avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

flutter_keyboard_visibility's Issues

FlutterKeyboardVisibilityPlugin cannot find symbol Type on line 91

Hi, I am getting this error when building an apk. Complete log :


flutter_keyboard_visibility-4.0.4\android\src\main\java\com\jrai\flutter_keyboard_visibili
ty\FlutterKeyboardVisibilityPlugin.java:91: error: cannot find symbol
        isVisible = insets.isVisible(WindowInsetsCompat.Type.ime());
                                                       ^
  symbol:   variable Type
  location: class WindowInsetsCompat
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':flutter_keyboard_visibility:compileReleaseJavaWithJavac'.

I have flutter version 1.22.5.

error: package androidx.annotation does not exist

Building plugin flutter_keyboard_visibility...
Running Gradle task 'assembleAarRelease'...
Running Gradle task 'assembleAarRelease'... Done 7,3s
/Users/ids/Downloads/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-3.2.2/android/src/main/java/com/jrai/flutter_keyboard_visibility/FlutterKeyboardVisibilityPlugin.java:9: error: package androidx.annotation does not exist
import androidx.annotation.NonNull;
/Users/ids/Downloads/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-3.2.2/android/src/main/java/com/jrai/flutter_keyboard_visibility/FlutterKeyboardVisibilityPlugin.java:25: error: cannot find symbol
public void onAttachedToEngine(@nonnull FlutterPluginBinding flutterPluginBinding) {
symbol: class NonNull
location: class FlutterKeyboardVisibilityPlugin
/Users/ids/Downloads/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-3.2.2/android/src/main/java/com/jrai/flutter_keyboard_visibility/FlutterKeyboardVisibilityPlugin.java:50: error: cannot find symbol
public void onDetachedFromEngine(@nonnull FlutterPluginBinding binding) {
symbol: class NonNull
location: class FlutterKeyboardVisibilityPlugin
/Users/ids/Downloads/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-3.2.2/android/src/main/java/com/jrai/flutter_keyboard_visibility/FlutterKeyboardVisibilityPlugin.java:55: error: cannot find symbol
public void onAttachedToActivity(@nonnull ActivityPluginBinding binding) {
symbol: class NonNull
location: class FlutterKeyboardVisibilityPlugin
/Users/ids/Downloads/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-3.2.2/android/src/main/java/com/jrai/flutter_keyboard_visibility/FlutterKeyboardVisibilityPlugin.java:65: error: cannot find symbol
public void onReattachedToActivityForConfigChanges(@nonnull ActivityPluginBinding binding) {
symbol: class NonNull
location: class FlutterKeyboardVisibilityPlugin
5 errors
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':compileReleaseJavaWithJavac'.
Compilation failed; see the compiler error output for details.
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Get more help at https://help.gradle.org
BUILD FAILED in 6s
The plugin flutter_keyboard_visibility could not be built due to the issue above.

Does anyone know how I can fix?

Error building for production

/Users/hdd/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-4.0.2/android/src/main/java/com/jrai/flutter_keyboard_visibility/FlutterKeyboardVisibilityPlugin.java
:9: error: cannot find symbol
import androidx.annotation.NonNull;
^
symbol: class NonNull
location: package androidx.annotation

Do I need to do anything in dispose() ?

@OverRide
void initState() {
super.initState();
_keyboardState = KeyboardVisibility.isVisible;
KeyboardVisibility.onChange.listen((bool visible) {
debugPrint("test test");
setState(() {
_keyboardState = visible;
});
});
}

This is my code. Should I do something in dispose() when I leave current page?

Because I receive some wrong message in DEBUG CONSOLE.

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose(): _BindBankCardPageState#e57ee(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
#0 State.setState. (package:flutter/src/widgets<…>

Version solving failed when using flutter_keyboard_visibility: ^4.0.4 with cloud_firestore >=1.0.0

Describe the bug
Can't use the latest null safe version ^4.0.4 with cloud firestore version >=1.0.0 as version solving fails. And the following message is thrown.

Because cloud_firestore >=1.0.0 depends on firebase_core_platform_interface ^4.0.0 and no versions of firebase_core_platform_interface match >4.0.0 <5.0.0, cloud_firestore >=1.0.0 requires firebase_core_platform_interface 4.0.0.
And because firebase_core_platform_interface 4.0.0 depends on plugin_platform_interface ^2.0.0, cloud_firestore >=1.0.0 requires plugin_platform_interface ^2.0.0.
And because flutter_keyboard_visibility >=4.0.0 <5.0.0-nullsafety.0 depends on flutter_keyboard_visibility_platform_interface ^1.0.1 which depends on plugin_platform_interface ^1.0.3, cloud_firestore >=1.0.0 is incompatible with flutter_keyboard_visibility >=4.0.0 <5.0.0-nullsafety.0.
So, because project_web depends on both cloud_firestore ^1.0.0 and flutter_keyboard_visibility ^4.0.4, version solving failed.
pub get failed (1; So, because project_web depends on both cloud_firestore ^1.0.0 and flutter_keyboard_visibility ^4.0.4, version solving failed.) 

To Reproduce
Steps to reproduce the behavior:

  1. Use flutter_keyboard_visibility: ^4.0.4 with cloud_firestore >=1.0.0
  2. Click on Pub get
  3. Go to messages
  4. See error : )

Info (please complete the following information):
flutter_keyboard_visibility version: ^4.0.4

flutter doctor output:

C:\src\flutter\bin\flutter.bat doctor --verbose
[√] Flutter (Channel stable, 2.0.2, on Microsoft Windows [Version 10.0.19042.867], locale en-IN)
    • Flutter version 2.0.2 at C:\src\flutter
    • Framework revision 8962f6dc68 (6 days ago), 2021-03-11 13:22:20 -0800
    • Engine revision 5d8bf811b3
    • Dart version 2.12.1

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at C:\Users\user\AppData\Local\Android\sdk
    • Platform android-S, build-tools 30.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 4.1.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] Connected device (3 available)
    • sdk gphone x86 (mobile) • emulator-5554 • android-x86    • Android 11 (API 30) (emulator)
    • Chrome (web)            • chrome        • web-javascript • Google Chrome 89.0.4389.90
    • Edge (web)              • edge          • web-javascript • Microsoft Edge 89.0.774.54

• No issues found!
Process finished with exit code 0

Failure building app for AndroidX

Hi I was trying to build an app that worked otherwise perfectly with the debug version but stumble upon an error relating to androidX. My project is androidx ready as show in gradle properties. Here are the error message:


PS D:\codes\nhapp> flutter build apk       
You are building a fat APK that includes binaries for android-arm, android-arm64, android-x64.
If you are deploying the app to the Play Store, it's recommended to use app bundles or split the APK to reduce the APK size.
    To generate an app bundle, run:
        flutter build appbundle --target-platform android-arm,android-arm64,android-x64
        Learn more on: https://developer.android.com/guide/app-bundle
    To split the APKs per ABI, run:
        flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi
        Learn more on:  https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split

FAILURE: Build failed with an exception.


* What went wrong:
Execution failed for task ':url_launcher:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\ScriptKiddie\.gradle\caches\transforms-2\files-2.1\a528b13ac93e64cafa3d0480e2c93207\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     C:\Users\ScriptKiddie\.gradle\caches\transforms-2\files-2.1\a528b13ac93e64cafa3d0480e2c93207\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/ttcIndex not found.


* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 19s
Running Gradle task 'assembleRelease'...                                
Running Gradle task 'assembleRelease'... Done                      20.2s
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
Building plugin flutter_keyboard_visibility...
Running Gradle task 'assembleAarRelease'...                             
Running Gradle task 'assembleAarRelease'... Done                    7.3s

D:\apps\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_keyboard_visibility-3.2.2\android\src\main\java\com\jrai\flutter_keyboard_visibility\FlutterKeyboardVisibilityPlugin.java:9: error: cannot find symbol
import androidx.annotation.NonNull;
                          ^
  symbol:   class NonNull
  location: package androidx.annotation
D:\apps\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_keyboard_visibility-3.2.2\android\src\main\java\com\jrai\flutter_keyboard_visibility\FlutterKeyboardVisibilityPlugin.java:25: error: cannot find symbol
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
                                  ^
  symbol:   class NonNull
  location: class FlutterKeyboardVisibilityPlugin
D:\apps\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_keyboard_visibility-3.2.2\android\src\main\java\com\jrai\flutter_keyboard_visibility\FlutterKeyboardVisibilityPlugin.java:50: error: cannot find symbol
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
                                    ^
  symbol:   class NonNull
  location: class FlutterKeyboardVisibilityPlugin
D:\apps\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_keyboard_visibility-3.2.2\android\src\main\java\com\jrai\flutter_keyboard_visibility\FlutterKeyboardVisibilityPlugin.java:55: error: cannot find symbol
  public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
                                    ^
  symbol:   class NonNull
  location: class FlutterKeyboardVisibilityPlugin
D:\apps\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_keyboard_visibility-3.2.2\android\src\main\java\com\jrai\flutter_keyboard_visibility\FlutterKeyboardVisibilityPlugin.java:65: error: cannot find symbol
  public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
                                                      ^
  symbol:   class NonNull
  location: class FlutterKeyboardVisibilityPlugin
5 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileReleaseJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 7s


The plugin flutter_keyboard_visibility could not be built due to the issue above.

Keyboard is not detected in Android

I'm using this library since Flutter v1.0 and always worked fine... some time ago I updated to Flutter stable and to flutter_keyboard_visibility 0.8.0/2.0.0 due to AndroidX compatibility, and after that, the lib doesn't work anymore...

In iOS works fine..

My project was generated with Java for Android and Objective-C for iOS.

Was tested on devices listed bellow.

flutter doctor

[✓] Flutter (Channel stable, v1.12.13+hotfix.5, on Mac OS X 10.15.2 19C57, locale pt-BR)
    • Flutter version 1.12.13+hotfix.5 at /Users/emerson.siega/development/flutter
    • Framework revision 27321ebbad (5 months ago), 2019-12-10 18:15:01 -0800
    • Engine revision 2994f7e1e6
    • Dart version 2.7.0

 
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/emerson.siega/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 28.0.3
    • ANDROID_HOME = /Users/emerson.siega/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.4)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.4, Build version 11E146
    • CocoaPods version 1.9.1

[✓] Android Studio (version 3.4)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 37.0.1
    • Dart plugin version 183.6270
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)

[✓] VS Code (version 1.44.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.9.1

[✓] Connected device (3 available)
    • MotoG3                    • 0020798379                           • android-arm • Android 6.0 (API 23)
    • Android SDK built for x86 • emulator-5554                        • android-x86 • Android 7.0 (API 24) (emulator)
    • iPhone SE                 • 366E752D-695F-4490-9DF6-0AD88E142BA9 • ios         • com.apple.CoreSimulator.SimRuntime.iOS-13-4 (simulator)

• No issues found!

Keyboard visibility is not updated when changing screens on (some) Android devices

In my app, I have a screen A (which doesn't use keyboard visibility), but does have several controls, including text editors. This screen navigates to another screen B, which does use keyboard visibility. What I'm finding is: if the keyboard is visible on Screen A at the point of navigation, then isVisible returns true on screen B even though it's not. Furthermore, if I introduce a third screen C (which nether shows a keyboard nor uses keyboard visibility), and I navigate A (showing keyboard) -push-> C -pop-> A (now not showing keyboard) -push-> B (not showing keyboard), isVisible again returns true on B.

But only sometimes: I have a Galaxy Alpha (Android 5.02) which works properly every time, and I have a Huawei CLT-L09 (Android 10) which gets it wrong every time. (I've also seen the fault on some current Samsungs).

From my very brief perusal of the code, it would seem that when an edit control is unfocussed by a screen change, the original screen never gets rebuilt, which means that FlutterKeyboardVisibilityPlugin.onGlobalLayout() doesn't get called - and it doesn't get called when the new screens are being built, either.

I know this behaviour is outside your control, but I tried (and failed) to find any way to ask the module to reset its state based on the current state of the screen (rather than the tally of callbacks). Do you think it would be possible to modify the isVisible getter to really go and find out what's on the screen now (and reset the internal flag) rather than just trusting that all the notifications have arrived safely? (Or even, adding a "synchronise" function to do the same?) In the meantime, can you think of a workaround to force an update from the push and pop calls?

Thanks

Consider adding tests for KeyboardVisibility

The KeyboardVisibility class is quite simple, but it wouldn't hurt to lock it down with some tests.

Adding tests for KeyboardVisibility would expose some of the fundamental testing issues that I ran into in my recent PR for this library. It would also provide piece of mind for future contributions to ensure that nothing breaks.

To the extent possible, you might also consider adding tests on the platform side to ensure that the per-platform code queries the right platform APIs. This might be accomplished with Espresso tests or Robolectric tests for Android, and EarlGray tests for iOS.

Doesn't work at all

final keyboardVisibilityController = KeyboardVisibilityController();
final bool keyboardVisible = keyboardVisibilityController.isVisible;

  print('keyboardVisible');
  print(keyboardVisible);

Keyboard is visible, but it returns false. I'm on Android. Latest version.

When open keyboard, automatically closed

I receive in console

W/IInputConnectionWrapper(14786): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(14786): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(14786): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper(14786): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(14786): endBatchEdit on inactive InputConnection

The keyboard not stay open when open, any idea? If disable o remove the listen, the keyboard stay open.

onChange no longer emiting values in 3.0.0

Currently running Flutter 1.17.2, on a Pixel 2.

Upon upgrading to version 3.0.0, the onChange function no longer emits values

This is the code I'm running (_clearFocus is just a function that clears the focus from text fields) :

KeyboardVisibility.onChange.listen((isVisible) {
      if (!isVisible) {
        _clearFocus();
      }
    });

Dispose keyboard listener on widget dispose

I have a code snippet like this in my initState

    KeyboardVisibility.onChange.listen((bool visible) {
      if (!visible) {
        setState(() {
          showTodoTitleEdit = false;
        });
      }
    });

And this is error I get

E/flutter ( 4408): [ERROR:flutter/lib/ui/ui_dart_state.cc(171)] Unhandled Exception: setState() called after dispose(): _TodoPageState#4ab5a(lifecycle state: defunct, not mounted, tickers: tracking 0 tickers)
E/flutter ( 4408): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter ( 4408): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 4408): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().

I have checked both examples there is no such thing as disposing isn't this actually necessary? I can fix it by checking mounted but I think that's a memory leak

Better example for stream on keyboard

Thank you for this library, I think is really helpful!

Just one remark, in your example please provide to the users how to close the stream or at least mention it, so junior devs will not fall into a trap.

[!] No podspec found for `flutter_keyboard_visibility_web` in `.symlinks/plugins/flutter_keyboard_visibility_web/ios`

flutter_keyboard_visibility: ^4.0.2

When I execute "pod install" in the ios directory, this is log:
pod install
Analyzing dependencies
[!] No podspec found for flutter_keyboard_visibility_web in .symlinks/plugins/flutter_keyboard_visibility_web/ios

How can I fix the problem? Thanks.

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 1.22.3, on Mac OS X 10.15.7 19H15, locale zh-Hans-CN)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
[✓] Android Studio (version 4.0)
[✓] VS Code (version 1.51.1)

pod --version
1.9.3

Deprecated API

The package is awesome and well done, but please, update it with non-deprecated API

Testing guide

Why did you make your KeyboardVisibility class with static methods? It would be useful to mock onChange stream and isVisible getter instead of calling setVisibility.

Update plugin_platform_interface to 2.0.0

Other packages are already using plugin_platform_interface 2.0.0 for null-safety and I got a version solving error because this package is using 1.1.0-nullsafety.1. Would it be possible to update?

onChange listener it's called twice

Describe the bug
onChange listener it's called twice

To Reproduce
Steps to reproduce the behavior:

  1. Create a StatefulWidget and subscribe directly to the listener on the initState
  2. Add a single TextField
  3. Click on the input to display the keyboard
  4. See the onChange callback it's called twice with the true state. Close the keyboard and see the onChange callback it's called twice with the false state.

Expected behavior
The onChange callback should only be executed once (both for keyboard open and close)

Info (please complete the following information):
flutter_keyboard_visibility version: 4.0.4
Tested on Android Emulator with Flutter 1.22.6

Additional context
This bug doesn't happen on version 3.0.0. Callback behaves as expected.

It doesn't work on iOS

It runs normally in Android environment, but the error is reported when compiling under IOS system. A look shows that there is no IOS content in this web package, how to remove this reference?

pakage version:
flutter_keyboard_visibility: 4.0.2

Error:
[!] No podspec found for flutter_keyboard_visibility_web in .symlinks/plugins/flutter_keyboard_visibility_web/ios

flutter_keyboard_visibility: 5.0.2 won't compile for Android

When trying to compile for Android; we get the following issue.

/Users/me/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-5.0.2/android/src/main/java/com/jrai/flutter_keyboard_visibility/FlutterKeyboardVisibilityPlugin.java:91: error: cannot find symbol
        isVisible = insets.isVisible(WindowInsetsCompat.Type.ime());
                                                       ^

Screenshot 2021-05-15 at 10 47 22

Plugin crashes on registering in background

Hi.

When registering plugin in background next line causes a crash. As I understand it is redundant since onAttachedToActivity does listener registration and after removing it nothing will change.

Stacktrace:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference at android.app.ActivityThread.handleCreateService(ActivityThread.java:3965) at android.app.ActivityThread.access$1500(ActivityThread.java:219) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1875) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7356) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference at com.jrai.flutter_keyboard_visibility.FlutterKeyboardVisibilityPlugin.listenForKeyboard(FlutterKeyboardVisibilityPlugin.java:105) at com.jrai.flutter_keyboard_visibility.FlutterKeyboardVisibilityPlugin.registerWith(FlutterKeyboardVisibilityPlugin.java:41) at io.flutter.plugins.GeneratedPluginRegistrant.registerWith(GeneratedPluginRegistrant.java:53)

Deprecated API on Flutter 2

Hello first of all thank you for this package.

I noticed the following warning whenever I attempt to build an apk:

Note: C:\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_keyboard_visibility-5.0.0\android\src\main\java\com\jrai\flutter_keyboard_visibility\FlutterKeyboardVisibilityPlugin.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details.

It is not causing any problems on my end but it seems to me that some dependencies need to be updated.

Thank you

Animate TextFormField attached to the top of the keyboard

I want to put a TextFormField which moves along with the keyboard.
This is standard behaviour as in many apps like whatsapp etc..
Is there a way to know exact curve/duration/height of the keyboard with this Package so that we can do the same for the TextFormField using a AnimatedPosition

Deprecated API

While compiling app, I am get this message about:

flutter_keyboard_visibility-3.2.2/android/src/main/java/com/jrai/flutter_keyboard_visibility/FlutterKeyboardVisibilityPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

Keyboard becomes Visible When accessing Drawer

Hi. Have you tested this kind of output?
It is the same implementation as KeyboardDismissOnTap widget.
I might submit an issue to the flutter repository, but it is somehow related to this too.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: KeyboardDismissOnTap(),
    );
  }
}
/// Tap the TextField first, then tap anywhere to close it.
/// Then Open the drawer in the appbar. the keyboard layout will show
/// despite the method has been unscoped.
class KeyboardDismissOnTap extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        final currentScope = FocusScope.of(context);
        if (!currentScope.hasPrimaryFocus) {
          currentScope.unfocus();
        }
      },
      child: Scaffold(
        appBar: AppBar(),
        drawer: Drawer(),
        body: Column(
          children: [
            Text("Tap the textfield, then tap anywhere to close it, then tap on the drawer. The keyboard visibility will open"),
            TextField(),
                    ],
                  ),
                );
              },
            )
          ],
        ),
      ),
    );
  }
}

Removable listener

Please add possibility to remove listeners added via onChange.listen method.
Reason: if we pass a closure to listen, which references some variables of widget, then after widget is disposed, the closure keeps firing on visibility change, and it tries to access variable which are long gone.

Keyboard visibility not detected on ios version 13.5.1 (iPhone 6s)

As the title suggests. It does not seem to register when the soft keyboard is extended on my old iPhone 6s.

Tested the same code on Android and it worked fine there, so it doesn't seem to be an issue with the code.

Tested it with a KeyboardVisibilityBuilder like in the example.

Cannot build project with v5.0.2

Describe the bug

I upgraded to the latest version for null safety support. However, now having trouble building my project:

C:\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_keyboard_visibility-5.0.2\android\src\main\java\com\jrai\flutter_keyboard_visibility\FlutterKeyboardVisibilityPlugin.java:91: error: cannot find symbol
        isVisible = insets.isVisible(WindowInsetsCompat.Type.ime());

To Reproduce
Steps to reproduce the behavior: Try to build project

Info (please complete the following information):
flutter_keyboard_visibility version: 5.0.2
Reproducible on platforms (Android, iOS, etc):
flutter doctor output:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.2, on Microsoft Windows [Version 10.0.19041.1052], locale en-AU)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[√] Chrome - develop for the web
[√] Android Studio
[√] VS Code (version 1.57.1)
[√] Connected device (3 available)

• No issues found!

Additional context

build.gradle:

buildscript {

    ext.kotlin_version = '1.5.10'

    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Consider eliminating public static references

I just submitted a PR with some new functionality for this package. In the process of extending this package and attempting to write tests, I noticed that this package relies on static members to query and notify clients of keyboard changes.

I would like to suggest migrating away from public static members.

Static members often interfere with testing practices. This is especially true for plugins where a connection is expected with the platform side. Such a connection is not easily faked.

In my PR I introduced a pretty ugly hack to facilitate a few simple tests. This was the result of those public static members.

An alternative to public static members is to provide only a singleton reference at the static level. For example:

final KeyboardVisibility keyboardVisibility = KeyboardVisibility.instance;
print('Is visible: ${keyboardVisibility.isVisible}');

With a singleton instance, one can replace the entire instance with a fake instance within tests. This avoids polluting the primary API surface with methods that should only be invoked during tests. It also lowers the likelihood that someone will inadvertently invoke a test method during production.

You can see this practice within Flutter if you look at bindings, for example:

WidgetsBinding.instance;
ServicesBinding.instance;

Android: Broken version 3.0.0, works in 0.7.0

I decided to update this library after awhile.
Currently broken on all our android devices (total 3) and I tested two emulators.
We revered back to 0.7.0 and everything is working again.

[✓] Flutter (Channel stable, v1.17.3, on Mac OS X 10.15.5 19F101, locale en-NO)
• Flutter version 1.17.3 at /Users/olly/flutter
• Framework revision b041144f83 (3 days ago), 2020-06-04 09:26:11 -0700
• Engine revision ee76268252
• Dart version 2.8.4

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at /Users/olly/Library/Android/sdk
• Platform android-R, build-tools 29.0.3
• ANDROID_HOME = /Users/olly/Library/Android/sdk
• ANDROID_SDK_ROOT = /Users/olly/Library/Android/sdk
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.5, Build version 11E608c
• CocoaPods version 1.9.1

[!] Android Studio (version 3.6)
• Android Studio at /Applications/Android Studio.app/Contents
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)

[✓] VS Code (version 1.45.1)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.11.0

MissingPluginException while using within widget test

When I try to use plugin within my widget test, although my tests do not fall and the golden test snapshots shows that the effect of setting keyboard visibility for testing is at play, I still get the MissingPluginException below in my logs. I've tried reloading, updating packages and all of that but it doesn't seem to be working.

══╡ EXCEPTION CAUGHT BY SERVICES LIBRARY ╞══════════════════════════════════════════════════════════
The following MissingPluginException was thrown while activating platform stream on channel
flutter_keyboard_visibility:
MissingPluginException(No implementation found for method listen on channel
flutter_keyboard_visibility)

When the exception was thrown, this was the stack:
#0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
<asynchronous suspension>
#1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
#2      EventChannel.receiveBroadcastStream.<anonymous closure> (package:flutter/src/services/platform_channel.dart:519:29)
#3      EventChannel.receiveBroadcastStream.<anonymous closure> (package:flutter/src/services/platform_channel.dart:505:64)
#8      KeyboardVisibility.onChange (package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart:22:12)
#9      _KeyboardVisibilityProviderState.initState (package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart:116:28)
#10     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4640:58)
#11     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
#12     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
#13     Element.updateChild (package:flutter/src/widgets/framework.dart:3211:20)
#14     RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1148:16)
#15     RenderObjectToWidgetElement.update (package:flutter/src/widgets/binding.dart:1126:5)
#16     RenderObjectToWidgetElement.performRebuild (package:flutter/src/widgets/binding.dart:1140:7)
#17     Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
#18     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2627:33)
#19     AutomatedTestWidgetsFlutterBinding.drawFrame (package:flutter_test/src/binding.dart:1006:18)
#20     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:284:5)
#21     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1113:15)
#22     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1052:9)
#23     AutomatedTestWidgetsFlutterBinding.pump.<anonymous closure> (package:flutter_test/src/binding.dart:879:9)
#26     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:72:41)
#27     AutomatedTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:866:27)
#28     WidgetTester.pumpWidget.<anonymous closure> (package:flutter_test/src/widget_tester.dart:441:22)
#31     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:72:41)
#32     WidgetTester.pumpWidget (package:flutter_test/src/widget_tester.dart:438:27)
#35     AutomatedTestWidgetsFlutterBinding.runAsync.<anonymous closure> (package:flutter_test/src/binding.dart:921:22)
#38     AutomatedTestWidgetsFlutterBinding.runAsync (package:flutter_test/src/binding.dart:919:26)
#39     WidgetTester.runAsync (package:flutter_test/src/widget_tester.dart:571:17)
#42     testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:140:29)
#55     AutomatedTestWidgetsFlutterBinding.runTest.<anonymous closure> (package:flutter_test/src/binding.dart:1099:17)
#56     AutomatedTestWidgetsFlutterBinding.runTest.<anonymous closure> (package:flutter_test/src/binding.dart:1087:35)
(elided 37 frames from class _FakeAsync, dart:async, and package:stack_trace)
════════════════════════════════════════════════════════════════════════════════════════════════════

flutter_keyboard_visibility bug in ios

Iam using Flutter in Mac -> Android studio and when I write pod install in the terminal. It show me

Analyzing dependencies
[!] No podspec found for `flutter_keyboard_visibility_web` in .symlinks/plugins/flutter_keyboard_visibility_web/ios`

flutter_typeahead plugin has a Dependencies with flutter_keyboard_visibility

Iam using flutter from one year ago, It is the first time it happen for me.
I cannot run the app. I don't have a plugin with this name flutter_keyboard_visibility_web in pubspec

How to fix it, thanks
@MisterJimson

Documentation version

I found a small issue on the documentation side

On this page https://pub.dev/packages/flutter_keyboard_visibility there is this text

Install 
Add the dependency to your pubspec.yaml

dependencies:
  flutter_keyboard_visibility: ^4.0.4

While on this page https://pub.dev/packages/flutter_keyboard_visibility/install the version is

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):


dependencies:
  flutter_keyboard_visibility: ^5.0.1

Thank you for your amazing project!

Only works second time keyboard is shown

KeyboardVisibilityBuilder(
builder: (context, isKeyboardVisible) {

I show the keyboard the first time. Trigger this view, it returns 'false'. Continues to show false until I hide and reshow the keyboard.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.