Flutter报错type '_AssertionError' is not a subtype of type 'String'如何解决
错误触发原因
- 直接触发点:代码位于
bookmark.dart第47行的Text(snapshot.error)。Text组件的入参要求为String类型,但当Future执行抛出异常时,snapshot.error存储的是_AssertionError类型的错误对象,无法直接作为String传入Text组件,因此触发类型不匹配报错。 - 根本异常来源:
getData()方法存在多处可能抛出断言错误的逻辑:- 从
SharedPreferences读取uid时未做判空,若uid为null,后续 Firestore 查询会报错 - 直接通过
snap['loved items']读取字段,若用户文档不存在、或者loved items字段未初始化,会抛出断言错误 - Firestore 的
whereIn查询最多仅支持传入10个比对值,若用户收藏的内容超过10条,查询会直接抛出异常
- 从
解决办法
- 第一步:修复UI层错误展示逻辑,将
Text(snapshot.error)修改为Text(snapshot.error.toString()),先把错误对象转为字符串再传入Text组件,直接解决本次类型报错问题。 - 第二步:完善
getData()方法的异常兼容逻辑:
Future<List> getData() async { try { SharedPreferences sp = await SharedPreferences.getInstance(); String? _uid = sp.getString('uid'); // uid为空直接返回空列表 if (_uid == null) return []; final DocumentReference ref = firestore.collection('users').doc(_uid); DocumentSnapshot snap = await ref.get(); // 判空+字段存在性校验 if (!snap.exists || !snap.data()!.containsKey('loved items')) return []; List d = snap.get('loved items') ?? []; List filteredData = []; if (d.isNotEmpty) { // 处理whereIn最多10条的限制,分批查询 for (int i = 0; i < d.length; i += 10) { List batch = d.sublist(i, min(i + 10, d.length)); QuerySnapshot batchSnap = await firestore .collection('contents') .where('timestamp', whereIn: batch) .get(); filteredData.addAll(batchSnap.docs); } } notifyListeners(); return filteredData; } catch (e) { debugPrint('获取收藏数据失败: $e'); return []; } }
- 可选优化:当前
FutureBuilder的future参数每次页面重绘都会重新调用getData()发起请求,建议将Future提前初始化(比如转成StatefulWidget在initState中调用getData()存储为state变量),避免重复请求。
内容的提问来源于stack exchange,提问作者ARUN BALAJI
相关产品推荐
相关产品推荐

