Flutter使用pdf包生成PDF时嵌套列表无法自动分页导致崩溃怎么办
问题原因
你使用的Wrap、Column组件在pdf包中属于不可拆分容器,会将内部所有内容作为一个整体渲染,一旦内容总高度超过单页可容纳高度就会触发溢出报错,MultiPage的自动分页能力仅对支持拆分的组件生效。
解决方案
将所有包裹列表的不可拆分容器替换为pdf包自带的支持自动分页的ListView组件,同时可以按需用Unbreakable组件包裹单组日期的所有内容,避免同一日期的记录被拆分到两页。
修改后的参考代码
class PdfParagraphApi { static Future<File> generate(title) async { final pdf = Document(); final customFont = Font.ttf(await rootBundle.load('assets/OpenSans-Regular.ttf')); pdf.addPage( MultiPage( build: (context) => <Widget>[ // 替换外层Wrap为ListView,支持自动分页 ListView( children: List<Widget>.generate(7, (index) { // 用Unbreakable包裹单天的所有内容,避免同日期记录被拆分 return Unbreakable( child: Container( margin: EdgeInsets.only(top: 3), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Header(child: Text( "08 Sep, 2021", style: TextStyle( color: PdfColors.purple300, fontWeight: FontWeight.bold, fontSize: 17 ) )), // 替换内层Wrap为Column,配合外层ListView实现分页 Column( children: List<Widget>.generate(9, (ind) { return cards(); }), ) ], ), ), ); }), ) ], ), ); return PdfApi.saveDocument(name: 'my_example.pdf', pdf: pdf); } static Widget cards() => Container( decoration: BoxDecoration( color: PdfColors.grey300, borderRadius: BorderRadius.circular(5) ), margin: EdgeInsets.only(bottom: 8), child: Container( // width: 300, margin: EdgeInsets.all(8.0), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Flexible( child: Container( margin: EdgeInsets.only(left: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( child: Text( "VISA", style: TextStyle( fontSize: 16 ) ), ), SizedBox(height: 5), Container( child: Text( "Token: 435645tRER3 Time: 12:45", ), ), ], ), ), Container( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.end, children: [ Row( children: [ Text( "GBP 56.07", maxLines: 1, style: TextStyle( fontWeight: FontWeight.bold ) ), Text( // " - ${charge.refundDetails.refundedAmount}", " - 45.87", style: TextStyle( fontSize: 12, color: PdfColors.red, ), ) ], ), SizedBox(height: 5), Text( "refunded", style: TextStyle( color: PdfColors.green), ), SizedBox(height: 5), Text( "Captured", ), ], ), ), ], ), ), ), ], ), ), ); }
补充说明
如果单天的交易记录本身就超过一整页的高度,去掉Unbreakable组件即可,允许单天的交易记录跨页展示。
内容的提问来源于stack exchange,提问作者Humayun Rahi
相关产品推荐
相关产品推荐

