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

Flutter实现点击按钮后TextField滚动展开并隐藏其他按钮

Flutter实现按钮组点击展开TextField的布局方案

核心实现思路

  • 用StatefulWidget维护选中按钮索引(初始为null表示未选中状态),以此控制布局切换。
  • 默认状态:通过Row横向排列四个按钮;选中状态:隐藏其余按钮,展开对应TextField并支持滚动。
  • 搭配AnimatedSwitcher实现布局切换的平滑过渡,避免生硬跳转。

完整可运行代码示例

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text("O|O|O|O布局示例")),
        body: const ButtonTextFieldLayout(),
      ),
    );
  }
}

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

  @override
  State<ButtonTextFieldLayout> createState() => _ButtonTextFieldLayoutState();
}

class _ButtonTextFieldLayoutState extends State<ButtonTextFieldLayout> {
  int? selectedIndex; // 记录选中的按钮索引,null代表未选中

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: AnimatedSwitcher(
        duration: const Duration(milliseconds: 300),
        transitionBuilder: (child, animation) {
          return FadeTransition(opacity: animation, child: child);
        },
        child: selectedIndex == null
            ? _buildButtonRow() // 默认按钮布局
            : _buildExpandedTextField(), // 选中后的TextField布局
      ),
    );
  }

  // 构建横向按钮组
  Widget _buildButtonRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: List.generate(4, (index) {
        return ElevatedButton(
          onPressed: () => setState(() => selectedIndex = index),
          child: Text("按钮${index + 1}"),
        );
      }),
    );
  }

  // 构建展开的TextField及返回按钮
  Widget _buildExpandedTextField() {
    return SingleChildScrollView(
      child: Column(
        children: [
          TextField(
            decoration: InputDecoration(
              hintText: "这是按钮${selectedIndex! + 1}对应的输入框",
              border: const OutlineInputBorder(),
            ),
            maxLines: null, // 支持多行输入,自动适配滚动
          ),
          const SizedBox(height: 16),
          TextButton(
            onPressed: () => setState(() => selectedIndex = null),
            child: const Text("返回按钮组"),
          ),
        ],
      ),
    );
  }
}

关键细节优化

  • 状态切换逻辑:通过setState更新selectedIndex,触发AnimatedSwitcher自动完成布局切换。
  • 滚动适配:用SingleChildScrollView包裹输入区域,确保输入内容过多时可正常滚动。
  • 动画自定义:示例用了淡入淡出过渡,你也可以替换成SizeTransition实现缩放式切换,提升交互质感。
  • 扩展交互:如果需要点击空白区域收起输入框,可以在Scaffold外层添加GestureDetector监听空白点击事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:27:12