You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Container根据子组件TextFormField自动调整尺寸?

解决Flutter中TextFormField容器随内容自适应高度的问题

要让带背景的Container随TextFormField的输入内容自动调整高度,只需做以下两处修改:

  • 移除Container的固定高度:你当前给Container设置了height:75,这会强制容器保持固定尺寸,删除该属性后,Container会自动根据子组件的高度调整自身大小。
  • 优化TextFormField的内边距:原有的contentPadding仅设置了左内边距,补充上下内边距可以让文本框内容显示更合理,同时确保容器能正确包裹文本框。

不需要额外监听用户的换行操作,因为你已经给TextFormField设置了maxLines: null,它会自动根据输入内容增加行数,容器只要不固定高度就会跟着适配。

修改后的完整代码:

import 'package:flutter/material.dart';

class MultiLineTextField extends StatefulWidget {
  const MultiLineTextField({super.key});

  @override
  State<MultiLineTextField> createState() => _MultiLineTextFieldState();
}

class _MultiLineTextFieldState extends State<MultiLineTextField> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: SingleChildScrollView(
        child: Column(
          children: [
            //Other widgets
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20),
              color: const Color.fromARGB(47, 255, 255, 255),
              // 移除固定height属性
              child: Padding(
                padding: const EdgeInsets.all(15.0),
                child: TextFormField(
                  autovalidateMode: AutovalidateMode.always,
                  maxLines: null,
                  cursorHeight: 17,
                  cursorColor: Colors.white,
                  decoration: const InputDecoration(
                    // 调整contentPadding,增加上下内边距
                    contentPadding: EdgeInsets.fromLTRB(12, 12, 0, 12),
                    border: OutlineInputBorder(),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.white),
                    ),
                    icon: Icon(Icons.location_on),
                    counterText: '',
                    labelText: 'Address',
                    labelStyle: TextStyle(
                      color: Colors.white,
                    ),
                  ),
                  validator: (value) {},
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者Twisha Solgama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:20:05