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

Flutter Row内组件过大导致水平溢出问题求助

解决Flutter布局水平溢出问题

问题分析

你的布局里,垂直滚动的ListView在水平滚动容器内没有明确宽度约束,会试图占据无限宽度,再加上右侧固定宽2000的组件,直接触发水平溢出。之前用SingleChildScrollView包裹Row无效,核心原因是没正确处理子组件的宽度约束。

修复方案

以下是调整后的代码,核心改动两点:

  • 用SingleChildScrollView + Row替代水平ListView,贴合你原始的Row布局需求
  • 给左侧垂直ListView添加宽度约束,用Expanded让它占据右侧固定组件之外的剩余水平空间,同时保留垂直滚动功能
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(
      title: ' Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
 getCard(int level){
    double indentation=5.0*level;
    return Padding(
      padding: EdgeInsets.only(left: indentation),
      child: Card(
        color: const Color(0xFFF5F5F5),
        child: ListTile(
          title: Text('List Item ${level + 1}'),
          subtitle: Text('Description for List Item ${level + 1}'),
          dense: true,
        ),
      ),
    );
  }
  getListView(){
    return ListView.builder(
      itemCount: 25,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap:(){
            setState(() {});
          },
          child: getCard(index),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: [
                  Expanded(
                    child: getListView(),
                  ),
                  const SizedBox(
                    width: 2000,
                    child: Text("A widget with a large size width"),
                  ),
                ],
              ),
            ),
          ),
          const Text("this needs to be at the bottom of the screen"),
        ],
      ),
     );
  }
}

额外调整选项

如果希望左侧ListView宽度固定(比如占屏幕宽度70%),可以把Expanded替换为SizedBox,结合MediaQuery获取屏幕尺寸:

SizedBox(
  width: MediaQuery.of(context).size.width * 0.7,
  child: getListView(),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:31:24