屏幕键盘出现时隐藏FAB

时间:2018-01-19 09:02:51

标签: material-design flutter floating-action-button

在Flutter中,如何在屏幕键盘出现时隐藏FAB button

当屏幕键盘显示时,FAB按钮会覆盖其他元素。

enter image description here

3 个答案:

答案 0 :(得分:9)

您可以通过使用viewInsets检查键盘可见性来实现它,并根据它隐藏fab。

示例:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    title: "Example",
    home: new FabHideOnKeyboard(),
  ));
}

class FabHideOnKeyboard extends StatefulWidget {
  @override
  _FabHideOnKeyboardState createState() => new _FabHideOnKeyboardState();
}

class _FabHideOnKeyboardState extends State<FabHideOnKeyboard> {
  @override
  Widget build(BuildContext context) {
    final bool showFab = MediaQuery.of(context).viewInsets.bottom==0.0;
    return Scaffold(
      resizeToAvoidBottomPadding: true,
      body:Container(
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("TextField:"),
            TextField()
          ],
        ),
      ),
      floatingActionButton: showFab?Icon(Icons.add):null,
    );
  }
}

希望有所帮助!

答案 1 :(得分:6)

FloatingActionButton小部件包裹Visibility,并用bool值控制可见性。

片段:
Widget build(context) {
  bool keyboardIsOpen = MediaQuery.of(context).viewInsets.bottom != 0;
  return Scaffold(
    body: // ...
    floatingActionButton: Visibility(
      visible: !keyboardIsOpen,
      child: // your FloatingActionButton
    ),
  );
}

当按钮消失并出现时,该解决方案也摆脱了动画。

请确保您已经为类extends StatefulWidget创建了状态

答案 2 :(得分:1)

为了将来参考,这是一个遵循 https://github.com/flutter/flutter/issues/26100 基本思想的实现,但使用现有的 mixin 来减少怪癖和代码:

class FixedCenterDockedFabLocation extends StandardFabLocation
    with FabCenterOffsetX, FabDockedOffsetY {
  const FixedCenterDockedFabLocation();

  @override
  String toString() => 'FloatingActionButtonLocation.fixedCenterDocked';

  @override
  double getOffsetY(
      ScaffoldPrelayoutGeometry scaffoldGeometry, double adjustment) {
    final double contentBottom = scaffoldGeometry.contentBottom;
    final double bottomMinInset = scaffoldGeometry.minInsets.bottom;
    if (bottomMinInset > 0) {
      // Hide if there's a keyboard
      return contentBottom;
    }
    return super.getOffsetY(scaffoldGeometry, adjustment);
  }
}

然后您可以像 floatingActionButtonLocation: const FixedCenterDockedFabLocation(), 一样简单地使用它(不要忘记 const ;))。

随意使用此代码,不受限制或归属。