Flutter中Notifier构造器未定义及后续构造器名称报错求助
解决Flutter中Notifier构造器未定义及构造器名称错误问题
初始问题:构造器“未定义”报错
你的TrxnNotifier.fromFirestore是命名构造器,但调用时错误地将其当成实例方法使用。
原定义代码:
class TrxnNotifier extends Notifier<Trxn> { TrxnNotifier.fromFirestore(Map<String, dynamic> firestore) : trxnId = firestore['trxnId'], userId = firestore['userId'], companyId = firestore['companyId']; }
调用代码的问题:你通过ref.read(trxnNotifierProvider.notifier)获取了TrxnNotifier的实例,然后尝试调用fromFirestore——但这是构造器,作用是创建新实例,不能通过已有实例调用。
正确调用方式:直接通过类名调用命名构造器创建新实例,修改dashboard.dart代码如下:
final trxnStreamProvider = StreamProvider.autoDispose<List<Trxn>>((ref) { final stream = firestoreService .getCompanyTrxns(ref.read(globalsNotifierProvider).companyId!); return stream.map((snapshot) => snapshot.docs.map((doc) => TrxnNotifier.fromFirestore(doc.data() as Map<String, dynamic>)) .toList()); });
更新后问题:构造器名称错误报错
你修改后的代码去掉了命名构造器的类名前缀,违反了Dart的构造器规则——构造器名称必须与类名匹配:要么是默认构造器(直接写TrxnNotifier(...)),要么是命名构造器(TrxnNotifier.fromFirestore(...))。
方案1:改为实例方法(更新已有实例属性)
如果想让fromFirestore用来更新已有实例的属性,需要将其定义为实例方法,用{}包裹方法体:
class TrxnNotifier extends Notifier<Trxn> { // 定义默认构造器(无其他构造器时可省略,但显式写出更清晰) TrxnNotifier(); // 实例方法:更新当前实例的属性 void fromFirestore(Map<String, dynamic> firestore) { trxnId = firestore['trxnId']; userId = firestore['userId']; companyId = firestore['companyId']; // 若需更新Notifier状态,需调用state = ...(根据你的Trxn类结构调整) } }
此时你原来的调用方式即可正常使用,因为fromFirestore已成为实例方法。
方案2:保留命名构造器(创建新实例)
如果仍想用构造器创建新实例,需保留命名构造器的正确格式:
class TrxnNotifier extends Notifier<Trxn> { // 命名构造器必须以类名开头 TrxnNotifier.fromFirestore(Map<String, dynamic> firestore) : trxnId = firestore['trxnId'], userId = firestore['userId'], companyId = firestore['companyId']; }
调用时仍按初始问题的正确方式,用TrxnNotifier.fromFirestore(...)创建新实例。
内容的提问来源于stack exchange,提问作者LostTexan
相关产品推荐
相关产品推荐

