Flutter Drawer关闭图标超出布局触发overflow报错问题问询
Flutter Drawer外侧放置关闭按钮及溢出报错解决方案
横向溢出报错根源:头部Row的所有子组件固定宽度总和(70+16+129+50=265)超出了外层容器设定的250宽度,导致尾部的关闭按钮区域显示不下触发溢出提示。
方案1:规范实现关闭图标在Drawer外侧(推荐)
完全符合你“关闭图标放在Drawer布局外侧”的需求,不会占用Drawer内部内容宽度,从根源避免溢出,同时保留Drawer内部滚动能力:
import 'package:flutter/material.dart'; // Dart规范类名使用大驼峰 class TempDrawer extends StatelessWidget { @override Widget build(BuildContext context) { return Stack( clipBehavior: Clip.none, // 允许子组件超出Stack边界显示,不会裁剪外侧的关闭按钮 children: [ Container( width: 250, child: Drawer( child: SafeArea( child: Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: FractionalOffset.bottomCenter, colors: [Color(0xffa4151a), Color(0xffe34b3d)], stops: [0, 1], ), ), child: ListView( padding: const EdgeInsets.zero, children: <Widget>[ Padding( padding: const EdgeInsets.only(left: 16, top: 16, right: 16), child: Row( children: [ ClipOval( child: Image( image: const AssetImage("images/face.png"), fit: BoxFit.cover, height: 70, width: 70, ), ), const SizedBox(width: 16), // 用户名改用Expanded占剩余空间,适配不同长度的用户名 Expanded( child: Text( "Alex assdsddff", overflow: TextOverflow.clip, style: const TextStyle(color: Colors.white), ), ), ], ), ), const Divider(color: Colors.white, indent: 20, endIndent: 20), Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Row( children: <Widget>[ const Icon(Icons.home_outlined, color: Colors.white), const Padding( padding: EdgeInsets.only(left: 8.0), child: Text("HOME", style: TextStyle(color: Colors.white)), ) ], ), ), // 可继续添加任意数量的组件,ListView天然支持滚动 ], ), ), ), ), ), // 关闭按钮独立放在Stack层,位置在Drawer外侧右上角 Positioned( right: -25, // 可自行调整数值控制按钮和Drawer的贴合程度 top: 20, child: GestureDetector( onTap: () => Navigator.pop(context), // 点击直接关闭侧边栏 child: ClipOval( child: Container( decoration: const BoxDecoration(color: Color(0xffa4151a)), width: 50, height: 50, child: const Icon(Icons.close, size: 40, color: Colors.white), ), ), ), ) ], ); } }
方案2:保留关闭图标在Drawer内部的修复方案
如果不需要把关闭按钮放在外侧,只需要把原来固定宽度的用户名容器替换为Expanded组件,自动适配Row的剩余空间即可消除溢出:
Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( width:70, child:ClipOval(child: Image( image: AssetImage("images/face.png"), fit: BoxFit.cover, height: 70, width: 70, )) ), const SizedBox(width: 16), // 替换原来固定宽度129的Container为Expanded,自动占满剩余可用宽度 const Expanded( child: Text("Alex assdsddff",overflow: TextOverflow.clip, style: TextStyle(color: Colors.white),) ), ClipOval( child:Container( decoration: BoxDecoration(color: Color(0xffa4151a)), width: 50, height: 50, child: const Icon(Icons.close,size: 40,color: Colors.white), ) ), ] ),
内容的提问来源于stack exchange,提问作者Alexandr
相关产品推荐
相关产品推荐

