Flutter中如何让容器固定尺寸并可滚动?附异常修复
解决两个问题的具体方案:
1. 右侧菜单固定尺寸并支持滚动
原来的Expanded会让两个菜单平分父容器高度,导致随窗口缩放。修改方式:
- 给每个右侧菜单设置固定高度(用
SizedBox替代Expanded) - 将两个菜单所在的
Column包裹在SingleChildScrollView中,当窗口高度小于两个菜单总高度时自动启用滚动
2. 修复窗口高度为0时的约束异常
网格区域的ConstrainedBox中,constraints.maxHeight -16在窗口高度不足16时会产生负数值,触发约束异常。通过max(0, ...)将高度限制在非负数范围,避免错误。
修正后的完整代码:
import 'package:flutter/material.dart'; import '../constants.dart'; import '../util/my_box.dart'; import '../util/my_tile.dart'; class DesktopScaffold extends StatefulWidget { const DesktopScaffold({Key? key}) : super(key: key); @override State<DesktopScaffold> createState() => _DesktopScaffoldState(); } class _DesktopScaffoldState extends State<DesktopScaffold> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: defaultBackgroundColor, appBar: myAppBar, body: LayoutBuilder( builder: (context, constraints) => Padding( padding: const EdgeInsets.all(8.0), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ // open drawer myDrawer, // first half of page Expanded( flex: 2, child: Column( children: [ // first 4 boxes in grid ConstrainedBox( // 修复负高度约束问题 constraints: BoxConstraints( maxHeight: max(0, constraints.maxHeight - 16), ), child: AspectRatio( aspectRatio: 4, child: SizedBox( width: double.infinity, child: GridView.builder( itemCount: 4, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4), itemBuilder: (context, index) { return MyBox(); }, ), ), ), ), // list of previous days Expanded( child: ListView.builder( itemCount: 7, itemBuilder: (context, index) { return const MyTile(); }, ), ), ], ), ), // second half of page Expanded( child: SingleChildScrollView( // 添加滚动支持 child: Column( children: [ // right menu 1 - 固定高度 SizedBox( height: 200, // 可自定义固定高度 child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: Colors.blue[400], ), ), ), ), // right menu 2 - 固定高度 SizedBox( height: 200, // 可自定义固定高度 child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: Colors.red[200], ), ), ), ), ], ), ), ), ], ), ), ), ); } }
内容的提问来源于stack exchange,提问作者GoodMan
相关产品推荐
相关产品推荐

