You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:12:52