Flutter TextEditingController无法在键盘上方滚动

Gan*_*pat 5 flutter

在android版本中,Flutter TextEditingController不会像在开始输入字段时默认文本字段那样在键盘上方滚动。我试图查看flutter示例目录中提供的示例应用程序,但是即使没有TextEditController的示例也具有这种行为。

有什么办法可以实现这一点。

提前致谢。

Rah*_*aee 8

很简单

如果您的文本字段在 5-10 个字段之间

 SingleChildScrollView(
     reverse: true,  // add this line in scroll view
     child:  ...
)
Run Code Online (Sandbox Code Playgroud)


Son*_*yen 7

我认为我的答案可能是这个问题最干净的解决方案:

@override
Widget build(BuildContext context) {
  /// Get the [BuildContext] of the currently-focused
  /// input field anywhere in the entire widget tree.
  final focusedCtx = FocusManager.instance.primaryFocus!.context;

  /// If u call [ensureVisible] while the keyboard is moving up
  /// (the keyboard's display animation does not yet finish), this
  /// will not work. U have to wait for the keyboard to be fully visible
  Future.delayed(const Duration(milliseconds: 400))
      .then((_) => Scrollable.ensureVisible(
            focusedCtx!,
            duration: const Duration(milliseconds: 200),
            curve: Curves.easeIn,
          ));
  /// [return] a [Column] of [TextField]s here...
}
Run Code Online (Sandbox Code Playgroud)

每次键盘启动或消失时,Flutter框架都会自动调用build()u的方法。您可以尝试在 IDE 中放置一个断点来自行找出此行为。

Future.delayed()首先会立即返回一个待处理的 Future,该 Future 将在 400 毫秒后成功完成。每当 Dart 运行时看到 a 时Future,它就会进入非阻塞 I/O 时间(= 非活动时间 = 异步时间 = 挂起时间,意味着 CPU 空闲等待某些事情完成)。当 Dart 运行时等待此Future完成时,它将继续执行下面的代码行来构建一列文本字段。并且当完成后,会立即跳回到this和execute方法Future的代码行。Future.then()

有关异步编程的更多信息,请参阅有关非阻塞 I/O 的简单可视化以及Flutter 团队


Gan*_*pat 4

感谢大家的有用回答@user2785693 指出了正确的方向。
我在这里找到了完整的工作解决方案: 这里

仅使用滚动或 focusNode.listner 的问题是,仅当我第一次专注于文本框时它才起作用,但如果我最小化键盘并再次单击已获得焦点的同一文本框,则列表器回调不会触发,所以自动滚动代码没有运行。解决方案是将“WidgetsBindingObserver”添加到状态类并覆盖“didChangeMetrics”函数。

希望这可以帮助其他人使 Flutter 表单更加用户友好。