欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Flutter點擊空白隱藏鍵盤的全局做法

 更新時間:2020年11月27日 10:26:24   作者:艾維碼  
這篇文章主要介紹了詳解Flutter點擊空白隱藏鍵盤的全局做法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

開發(fā)原生頁面的時候,在處理鍵盤事件上,通常的需求是,點擊輸入框外屏幕,要隱藏鍵盤,同樣的,這樣的需求也需要在 Flutter 上實現(xiàn),

Android 上的實現(xiàn)方式是在基類 Activity 里實現(xiàn)事件分發(fā),判斷觸摸位置是否在輸入框內(nèi)。

 /**
   * 獲取點擊事件
   */
  @CallSuper
  @Override
  public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.MotionEvent ) {
      View view = getCurrentFocus();
      if (isShouldHideKeyBord(view, ev)) {
        hideSoftInput(view.getWindowToken());
      }
    }
    return super.dispatchTouchEvent(ev);
  }

  /**
   * 判定當前是否需要隱藏
   */
  protected boolean isShouldHideKeyBord(View v, MotionEvent ev) {
    if (v != null && (v instanceof EditText)) {
      int[] l = {0, 0};
      v.getLocationInWindow(l);
      int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
      return !(ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom);
    }
    return false;
  }

  /**
   * 隱藏軟鍵盤
   */
  private void hideSoftInput(IBinder token) {
    if (token != null) {
      InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
      manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
    }
  }

那么在 Flutter 上如何實現(xiàn)呢?

許多文章的做法如下,每個包含TextField的屏幕中包裹GestureDetector,手動控制Focus。一旦失去焦點,就請求關閉鍵盤。這是一個臨時的解決方案,容易出錯,并且生成大量代碼。

GestureDetector(
  behavior: HitTestBehavior.translucent,
  onTap: () {
    // 觸摸收起鍵盤
    FocusScope.of(context).requestFocus(FocusNode());
  },
  child: *******
}

通常這種需求是對應整個 app 的,有沒有一勞永逸的方法呢?當然有,我們可以借助MaterialApp的builder方法,在 Navigator上方但在其他小部件下方插入小部件,僅添加了一個“全局” GestureDetector,它將為我們處理鍵盤關閉:

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

class MyApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return MaterialApp(
   title: 'Flutter Demo',
   theme: ThemeData(
    primarySwatch: Colors.blue,
    visualDensity: VisualDensity.adaptivePlatformDensity,
   ),
   builder: (context, child) => Scaffold(
    // Global GestureDetector that will dismiss the keyboard
    body: GestureDetector(
     onTap: () {
     hideKeyboard(context);
     },
     child: child,
    ),
   ),
   home: MyHomePage(title: 'Flutter Demo Home Page'),
  );
 }

 void hideKeyboard(BuildContext context) {
  FocusScopeNode currentFocus = FocusScope.of(context);
  if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
   FocusManager.instance.primaryFocus.unfocus();
  }
 }
}

當然也可以使用下面這個方法關閉鍵盤:

SystemChannels.textInput.invokeMethod('TextInput.hide');

這樣就全局控制,再也不用在每個頁面寫了。

到此這篇關于詳解Flutter點擊空白隱藏鍵盤的全局做法的文章就介紹到這了,更多相關Flutter點擊空白隱藏鍵盤內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論