Flutter的showModalBottomSheet 输入框被弹出的键盘挡住?

2022-09-20 16:37:29 浏览数 (1)

需求描述

最近在做项目的时候有这样一个需求:用户对已购买的商品进行评价,如果用户给差评,就必须输入原因。并且输入框是从底部弹起的一个单独层。

需求分析

拿到这个需求很简单,直接 showModalBottomSheet textfield组件就搞定。

代码语言:javascript复制
/// 忽略样式不管
showModalBottomSheet(
  isScrollControlled: true,  // !important
  builder: (BuildContext context) {
    return Container(
        child: TextField(
              keyboardType: TextInputType.text,
              autofocus: true,
            )
      );
  },
);

ok, 完成后运行后发现问题来了。

我点输入框后,弹出的键盘挡住了输入框。

我很方,键盘怎么就没有把输入框推上去呢,和我想的不太一样啊。

解决方法

使用 AnimatedPadding这个widget,我们来看看它的解释。嗯,是Padding的动画版本,我们利用它在键盘谈起的时候给我们的输入框加个padding就好了。万事大吉!!!

代码语言:javascript复制
/// Animated version of [Padding] which automatically transitions the
/// indentation over a given duration whenever the given inset changes.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=PY2m0fhGNz4}
///
/// Here's an illustration of what using this widget looks like, using a [curve]
/// of [Curves.fastOutSlowIn].
/// {@animation 250 266 https://flutter.github.io/assets-for-api-docs/assets/widgets/animated_padding.mp4}
///
/// See also:
///
///  * [AnimatedContainer], which can transition more values at once.
///  * [AnimatedAlign], which automatically transitions its child's
///    position over a given duration whenever the given
///    [AnimatedAlign.alignment] changes.
AnimatedPadding({
    Key key,
    @required this.padding,
    this.child,
    Curve curve = Curves.linear,
    @required Duration duration,
    VoidCallback onEnd,
  }) : assert(padding != null),
       assert(padding.isNonNegative),
       super(key: key, curve: curve, duration: duration, onEnd: onEnd);

修改后的代码

代码语言:javascript复制
/// 忽略样式不管
showModalBottomSheet(
  isScrollControlled: true,  // !important
  builder: (BuildContext context) {
    return AnimatedPadding(
      padding: MediaQuery.of(context).viewInsets, // 我们可以根据这个获取需要的padding
      duration: const Duration(milliseconds: 100),
      child: Container(
        child: TextField(
              keyboardType: TextInputType.text,
              autofocus: true,
            )
      ),
     );
  },
);


关于viewInsets的解释
 /// The parts of the display that are completely obscured by system UI,
  /// typically by the device's keyboard.
  ///
  /// When a mobile device's keyboard is visible `viewInsets.bottom`
  /// corresponds to the top of the keyboard.
  ///
  /// This value is independent of the [padding] and [viewPadding]. viewPadding
  /// is measured from the edges of the [MediaQuery] widget's bounds. Padding is
  /// calculated based on the viewPadding and viewInsets. The bounds of the top
  /// level MediaQuery created by [WidgetsApp] are the same as the window
  /// (often the mobile device screen) that contains the app.
  ///
  /// See also:
  ///
  ///  * [ui.window], which provides some additional detail about this property
  ///    and how it relates to [padding] and [viewPadding].

好了,本次分享就到这里,喜欢的点个赞哦

今日精选壁纸

0 人点赞