When the Flutter page pops up, you can set the resizeToAvoidBottomInset property of Scaffold to set the processing of the soft keyboard.
When this value is true, the page will be re-layouted. So how should we listen to Flutter's keyboard popups and page height changes?
Let's start with the Flutter keyboard pop-up. When the focus of an input box TextField changes, the focus change will be performed
_openOrCloseInputConnectionIfNeeded method:
if (_hasFocus && ()) { _openInputConnection(); } else if (!_hasFocus) { _closeInputConnectionIfNeeded(); (); }
Here, the show method of TextInputConnection will be called to open the keyboard:
void _show() { _channel.invokeMethod<void>(''); }
Here, this method will be called through the call of _show
// Android side implementationmImm = (InputMethodManager) ().getSystemService(Context.INPUT_METHOD_SERVICE); // TextInputHandler private void showTextInput(View view) { (); (view, 0); }
On the Android side, finally, call InputMethodManager to open the soft keyboard. The view here refers to FlutterView.
At this time, the View's onApplyWindowInsets will be called:
// FlutterView = navigationBarVisible ? () : guessBottomKeyboardInset(insets); updateViewportMetrics(); private int guessBottomKeyboardInset(WindowInsets insets) { int screenHeight = getRootView().getHeight(); // Magic number due to this being a heuristic. This should be replaced, but we have not // found a clean way to do it yet (Sept. 2018) final double keyboardHeightRatioHeuristic = 0.18; if (() < screenHeight * keyboardHeightRatioHeuristic) { // Is not a keyboard, so return zero as inset. return 0; } else { // Is a keyboard, so return the full inset. return (); } }
Here we can see that on the Android side, when the height of the soft keyboard is visible in the bottom bar, the bottom of the system window inset is taken.
If it is not visible, it will guess based on the proportion of bottom inset. When this height is greater than 0.18, it will be considered as a keyboard pop-up.
When it is determined that it is a soft keyboard, page redraw will be triggered by refreshing ViewportMetrics:
// FlutterView private void updateViewportMetrics() { if (!isAttached()) return; mNativeView .getFlutterJNI() .setViewportMetrics( , , , , , , , , , , , , , , ); }
metrics updated on the Dart side in the entry
@pragma('vm:entry-point') void _updateWindowMetrics( //...Omit parameters) { _invoke(, window._onMetricsChangedZone); }
After the above theoretical analysis, we can conclude that the height changes of the Flutter soft keyboard are reflected in the changes of metrics. The specific value is reflected in .
Summarize
This is the end of this article about the principle of Flutter soft keyboard. For more information about the principle of Flutter soft keyboard, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!