Flutter Firestore解析DocumentSnapshot时Object?类无[]运算符报错如何解决
Flutter Firestore UserModel 报错修复方案
报错原因
- cloud_firestore 2.0.0及以上版本优化了类型系统,
DocumentSnapshot.data()方法默认返回Object?类型,没有内置[]运算符,无法直接读取字段值。
修复方案
推荐使用泛型约束的规范写法,完整修复后的代码如下:
import 'package:cloud_firestore/cloud_firestore.dart'; class UserModel{ static const NUMBER = 'number'; static const ID = 'id'; String _number = ''; String _id = ''; String get number => _number; String get id => _id; // 给DocumentSnapshot添加泛型约束,明确存储的数据结构为Map<String, dynamic> UserModel.fromSnapshot(DocumentSnapshot<Map<String, dynamic>> snapshot){ final data = snapshot.data()!; _number = data[NUMBER]; _id = data[ID]; } }
可选优化(空安全兜底)
如果要避免字段缺失或快照为空导致的运行时异常,可以添加空值判断和默认值:
UserModel.fromSnapshot(DocumentSnapshot<Map<String, dynamic>> snapshot){ final data = snapshot.data(); _number = data?[NUMBER] ?? ''; _id = data?[ID] ?? ''; }
内容的提问来源于stack exchange,提问作者David Hedrin
相关产品推荐
相关产品推荐

