Flutter运行时异常求助:'String'不是'int'类型的'index'子类型
异常信息
[ERROR: flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' #0
异常定位:Products类的fetchAndSetProducts方法(路径:package:my_shop/providers/products.dart:60:7)
问题根源
该异常因使用字符串作为数组索引触发,核心原因是Firebase返回的数据结构与代码预期不匹配(预期Map却得到List),或代码中变量引用错误导致查询逻辑失效。
修复步骤
1. 修正Filter字符串的变量引用错误
fetchAndSetProducts方法中,filterString的equalTo参数错误写死为字符串"userId",而非引用变量$userId,导致查询逻辑完全错误,可能返回非预期数据结构。
原代码:
final filterString = filterByUser ? 'orderBy="creatorId"&equalTo="userId"' : '';
修改为:
final filterString = filterByUser ? 'orderBy="creatorId"&equalTo="$userId"' : '';
2. 增加数据类型校验
解析Firebase返回数据时,增加类型判断,避免将List当作Map处理,防止后续索引操作出错。
修改fetchAndSetProducts中的数据解析部分:
final response = await http.get(url); final decodedResponse = json.decode(response.body); // 确保返回的是Map结构 if (decodedResponse is! Map<String, dynamic>) { return; } final extractedData = decodedResponse; // ... final favoriteResponse = await http.get(url); final favoriteData = json.decode(favoriteResponse.body); // 确保favoriteData是Map或null final processedFavoriteData = (favoriteData is Map) ? favoriteData : null;
后续使用processedFavoriteData替代原favoriteData:
isFavorite: processedFavoriteData == null ? false : processedFavoriteData[prodId] ?? false,
3. 检查Firebase数据库结构
确保以下节点为对象结构(key为ID,value为对应数据),而非数组:
products节点:每个产品以其ID为key存储userFavorites/$userId节点:每个收藏项以产品ID为key存储
若数据库为数组结构,需调整为对象结构(Firebase Realtime Database更适合用对象存储结构化数据),或修改代码适配数组。
4. 修正Auth模块的Token返回逻辑
当前auth.dart中token getter在无效时返回空字符串,会导致Firebase请求返回错误,进而返回非预期JSON结构。修改为返回null,并在请求前校验:
修改auth.dart的token getter:
String? get token { if (_expiryDate != null && _expiryDate!.isAfter(DateTime.now()) && _token.isNotEmpty) { return _token; } return null; }
在fetchAndSetProducts开头增加Token校验:
if (authToken.isEmpty) { throw Exception('Authentication token is missing or invalid'); }
内容的提问来源于stack exchange,提问作者Tooraj rezaei

