当 TextFormFields 因错误展开时,SingleChildScrollView 内部出现底部溢出

问题描述 投票:0回答:1

我有一个注册页面,其中包含一堆 TextFormFields,这些 TextFormFields 位于 SingleChildScrollView 内,以便用户可以在键盘弹出时滚动。如果我在条目未通过验证时点击注册按钮,则 TextFormFields 的高度会扩展,因为错误文本会在下面弹出,并且我的小部件不再适合屏幕。我不想将

resizeToAvoidBottomInset=false
添加到我的脚手架中,因为这样底部的 TextFormFields 可能会隐藏在键盘下方。为什么 SingleChildScrollView 仍然不能与这些展开的小部件一起使用?

我的一些代码:

@override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Container(
            height: screenHeight - screenHeight * 0.03,
            child: Column(
              children: [
                // Back button here
                Spacer(),
                // Whole bunch of TextFormFields here
                SizedBox(height: screenHeight * 0.03),
              ],
            ),
          ),
        ),
      ),
    );
  }
flutter flutter-textformfield
1个回答
0
投票

您在 SingleChildScrollView 和 TextFormFields 中遇到的问题源于具有固定高度的容器,当发生验证错误时,该高度无法适应内容。当错误文本出现时,列的整体高度会增加,这可能会导致溢出问题,因为内容超出了屏幕高度。

建议的解决方案

  • 删除固定高度:而不是在
    上设置固定高度 容器,让它适应内容。这将允许
    SingleChildScrollView 在内容时正确处理滚动 扩大。使用扩展或删除
  • 垫片:如果使用垫片,您可能需要将其移除或重新考虑 它的位置,因为它可能会导致意外的布局问题。这是一个 已更新

您的代码版本:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: SafeArea(
      child: SingleChildScrollView(
        child: Column(
          children: [
            // Back button here
            // Example: IconButton to go back
            IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            SizedBox(height: 20), // Add some space
            // Whole bunch of TextFormFields here, e.g.:
            TextFormField(
              decoration: InputDecoration(labelText: 'Email'),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
            ),
            // Add more TextFormFields as needed
            SizedBox(height: 20), // Add some space
            ElevatedButton(
              onPressed: () {
                // Handle signup logic
              },
              child: Text('Sign Up'),
            ),
            SizedBox(height: 20), // Add some space
          ],
        ),
      ),
    ),
  );
}

其他提示:

  • 键盘处理:如果您想更多地控制键盘行为, 考虑使用 ResizeKeyboard 小部件或 MediaQuery 进行调整 动态填充/边距。
  • 表单验证:确保您的表单验证设置正确 并且您正在调用 setState 来触发重建 验证失败。这可确保显示任何错误消息 正确地。
© www.soinside.com 2019 - 2024. All rights reserved.