Flutter项目:改multi_image_picker选中图为横向ListView遇断言异常
嘿,我帮你梳理了这个问题,咱们一步步来解决:
你原本用multi_image_picker插件的Flutter项目运行正常,但把选中图片从GridView改成横向ListView展示时,触发了这个断言异常:
I/flutter (18429): Another exception was thrown: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 3723 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
I/chatty (18429): uid=10160(com.example.flutter_sample) 1.ui identical 7 lines
I/flutter (18429): Another exception was thrown: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 3723 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
D/EGL_emulation(18429): eglMakeCurrent: 0xe18058a0: ver 2 0 (tinfo 0xe18035c0)
问题根源
你现在的代码是在横向ListView里嵌套了一个横向GridView,还加了Expanded——这就踩了两个坑:
- 嵌套的同方向滚动组件会导致Flutter的渲染上下文混乱,触发那个断言错误
Expanded在横向ListView里完全没必要,因为ListView本身是可滚动容器,内部组件不需要强制拉伸
修复方案
其实完全不需要嵌套GridView,直接用横向ListView渲染图片列表就够了,调整后的代码如下:
Container( margin: EdgeInsets.symmetric(vertical: 20.0), height: 200.0, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: images.length, itemBuilder: (context, index) { Asset asset = images[index]; return Padding( // 可选:给图片之间添加横向间距,优化视觉效果 padding: EdgeInsets.symmetric(horizontal: 8.0), child: AssetThumb( asset: asset, width: 180, // 适配外层Container的高度,避免图片拉伸变形 height: 180, ), ); }, ), )
额外说明
如果你的需求其实是要在横向滚动里展示多行图片(比如类似横向的网格),那也不能直接嵌套GridView,得这么改:
Container( margin: EdgeInsets.symmetric(vertical: 20.0), height: 200.0, child: ListView( scrollDirection: Axis.horizontal, children: [ GridView.count( scrollDirection: Axis.vertical, // 网格用纵向滚动 crossAxisCount: 3, shrinkWrap: true, // 让网格自适应内容高度 physics: NeverScrollableScrollPhysics(), // 禁用网格自身的滚动,交给外层ListView控制 children: List.generate(images.length, (index) { Asset asset = images[index]; return AssetThumb( asset: asset, width: 100, height: 100, ); }), ), ], ), )
不过看你的需求是横向展示选中图片,第一种方案就完全够用啦。
内容的提问来源于stack exchange,提问作者Hoo

