Flutter中DartVM堆空间耗尽问题排查及代码修复请求
内存溢出原因排查与修复方案
核心问题分析
- 无限循环导致内存耗尽:代码中的for循环条件写错了——
for (int i = 1; 1 < 4; i++),这里的判断条件是1 < 4,这个表达式永远为true,循环会无限执行,不断创建Container组件,最终把堆内存占满,触发堆空间耗尽错误。 - 次要问题:部分
Color值格式错误,比如Color(0xff47569)只写了5位十六进制数,Flutter要求颜色值必须是6位(加上前缀共8位),虽然这不会直接引发内存溢出,但会导致渲染异常。
修复步骤
1. 修复无限循环
把循环条件改成基于变量i的判断,如果是要循环3次(i从1到3),应该写成:
for (int i = 1; i < 4; i++)
这样循环会在i等于4时自动终止,仅创建3个Container,避免无限占用内存。
2. 修正颜色值格式
把错误的Color(0xff47569)改成和代码中其他地方一致的6位十六进制值:
BoxShadow( color: Color(0xff475269).withOpacity(0.3), blurRadius: 5, spreadRadius: 1, )
修复后的完整代码
// 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: [ // 修复循环条件,避免无限创建组件 for (int i = 1; i < 4; i++) Container( margin: EdgeInsets.only(top: 10, bottom: 10), padding: EdgeInsets.symmetric(horizontal: 10), height: 160, 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( margin: EdgeInsets.only(top: 20, right: 10), height: 110, width: 120, decoration: BoxDecoration( color: Color(0xFF475269), borderRadius: BorderRadius.circular(20), ), ), Image.asset( "images/1.png", height: 150, width: 150, fit: BoxFit.contain, ) ], ), Padding( padding: EdgeInsets.symmetric(vertical: 30), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Nike Shoe', style: TextStyle( color: Color(0xff475269), fontSize: 23, fontWeight: FontWeight.w500, ), ), SizedBox( height: 1, ), Text( "Men's Shoe", style: TextStyle( color: Color(0xff475269).withOpacity(0.8), fontSize: 16), ) ]), ), SizedBox(width: 0), Row( children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 5), child: Text( "$50", style: TextStyle( color: Colors.redAccent, fontSize: 20, fontWeight: FontWeight.w500, ), ), ), SizedBox(width: 1), 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, ), ), ], ) ]), ) ]), ); } }
额外优化建议
- 如果后续需要加载更多列表项,建议用
ListView.builder替代Row+手动循环,它会按需加载组件,进一步降低内存占用。 - 检查
images/1.png的文件大小,过大的图片也会增加内存压力,建议提前压缩图片资源。
内容的提问来源于stack exchange,提问作者Ray Omiyi
相关产品推荐
相关产品推荐

