Flutter代码运行提示FlutterError,用SizedBox包裹Container仍出错求助
FlutterError 问题排查与修复
核心问题分析
代码里存在几个明确的错误点,直接导致FlutterError:
十六进制颜色值格式错误
BoxShadow中的颜色写为Color(0xff47569),十六进制颜色需要6位字符,这里少一位,应改为Color(0xff475269)(与代码中其他同色系颜色值保持一致)。布局约束冲突
内层Row使用了Spacer(),但外层Container未设置宽度,Row无法确定可用空间分配给Spacer,引发约束冲突。同时右侧SizedBox(width:70)的间距过大,容易导致小屏幕内容溢出。图片资源路径校验
需确保images/1.png已在pubspec.yaml中正确配置assets:assets: - images/1.png
修复后的完整代码
// ignore_for_file: prefer_const_constructors, file_names, prefer_const_literals_to_create_immutables, use_full_hex_values_for_flutter_colors import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class RowItemsWidget extends StatelessWidget { const RowItemsWidget({super.key}); @override Widget build(BuildContext context) { return SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ Container( margin: EdgeInsets.only(top: 10, bottom: 10, left: 15), padding: EdgeInsets.symmetric(horizontal: 10), height: 180, width: MediaQuery.of(context).size.width - 30, // 适配屏幕宽度,避免无约束 decoration: BoxDecoration( color: Color(0xfff5f9fd), borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Color(0xff475269).withOpacity(0.3), // 修复颜色值位数 blurRadius: 5, spreadRadius: 1, ) ]), child: Row(children: [ Stack( alignment: Alignment.center, children: [ Container( height: 120, width: 130, decoration: BoxDecoration( color: Color(0xFF475269), borderRadius: BorderRadius.circular(10), ), ), Image.asset( "images/1.png", height: 150, width: 150, fit: BoxFit.contain, ) ], ), SizedBox(width: 15), // 固定间距替代无约束的Spacer Padding( padding: EdgeInsets.symmetric(vertical: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Nike Shoe', style: TextStyle( color: Color(0xff475269), fontSize: 23, fontWeight: FontWeight.w500, ), ), SizedBox(height: 5), Text( "Men's Shoe", style: TextStyle( color: Color(0xff475269).withOpacity(0.8), fontSize: 16), ) ]), ), Spacer(), // 外层Container有明确宽度后,Spacer可正常工作 Row( children: [ Text( "\$50", style: TextStyle( color: Colors.redAccent, fontSize: 22, fontWeight: FontWeight.w500, ), ), SizedBox(width: 20), // 缩小间距避免小屏幕溢出 Container( padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Color(0xff475269), borderRadius: BorderRadius.circular(10)), child: Icon( CupertinoIcons.cart_fill_badge_plus, color: Colors.white, size: 25, ), ), ], ) ]), ) ]), ); } }
额外优化说明
- 用
MediaQuery.of(context).size.width - 30给外层Container设置宽度,既解决约束问题,又能适配不同屏幕尺寸。 - 调整右侧固定间距为20,避免小屏幕下内容超出容器范围。
内容的提问来源于stack exchange,提问作者Ray Omiyi
相关产品推荐
相关产品推荐

