dart 当我尝试在Flutter应用程序中使用通知程序类时,未定义通知程序类的构造函数

4ioopgfo  于 11个月前  发布在  Flutter
关注(0)|答案(1)|浏览(113)

我试图使用一个构造函数的通知,但构造函数是“未定义”的文件中,我试图使用它。
下面是provider.dart文件中定义的类:

class TrxnNotifier extends Notifier<Trxn> {
    TrxnNotifier.fromFirestore(Map<String, dynamic> firestore)
      : trxnId = firestore['trxnId'],
        userId = firestore['userId'],
        companyId = firestore['companyId'];
}

字符串
下面是我尝试在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) => 
      ref.read(trxnNotifierProvider.notifier).fromFirestore(doc.data() as Map<String, dynamic>))
      .toList());
});


在dashboard.dart文件中,我得到错误消息:The method 'fromFirestore' isn 't defined for the type 'TrxnNotifier'.
我该怎么做?谢谢

更新:

我就像你说的那样,但现在我得到了这个错误:

构造函数的名称必须与封闭类的名称匹配。dart(invalid_constructor_name)

下面是我现在的代码:

class TrxnNotifier extends Notifier<Trxn> {

  fromFirestore(Map<String, dynamic> firestore)
      : trxnId = firestore['trxnId'],
        userId = firestore['userId'],
        companyId = firestore['companyId'];


我没有像你说的那样在它周围{},但我不知道我会怎么做。
谢谢你的帮助。

r6l8ljro

r6l8ljro1#

您正在定义TrxnNotifier.fromFirestore,它是一个命名构造函数。命名构造函数通常如下调用:

TrxnNotifier.fromFirestore(...)

字符串
你所做的是从ref.read(trxnNotifierProvider.notifier)调用fromFirestoreref.read(trxnNotifierProvider.notifier)TrxnNotifier的一个示例,而不是类本身。如果你想从一个示例调用一个方法,在TrxnNotifier类中定义一个示例方法,如下所示:

class TrxnNotifier extends Notifier<Trxn> {
  fromFirestore(Map<String, dynamic> firestore) {
    // implementation
  }
}

相关问题