【问题标题】:Exception: Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist provider异常:错误状态:无法获取 DocumentSnapshotPlatform 上不存在提供程序的字段
【发布时间】:2021-11-27 21:48:16
【问题描述】:

我在 MyApp 上设置了提供程序流。

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final AuthService _auth = AuthService();
    String? _userId = _auth.user?.uid;
    return StreamProvider<UserProfileModel?>(
        initialData: null,
        create: (_) => DatabaseService().userProfileData(_userId),
        builder: (context, snapshot) {
          final userT = context.watch<UserProfileModel?>();
          final userType = userT?.userType;
          print('User type is: $userType');
          return MaterialApp(
            color: Colors.blueAccent,
            debugShowCheckedModeBanner: false,
            //home: TOCScreen(),
            home: _auth.user == null
                ? StartScreenMsg()
                : userType == 'Creditor'
                    ? CreditorHomePage()
                    : userType == 'Financial Recovery\nWorker'
                        ? FinancialHomePage()
                        : userType == 'Debtor'
                            ? DebtorHomePage()
                            : HomeScreen(),

这会从数据库中获取 userType 并相应地显示屏幕,它工作正常,但每当我运行应用程序时,它都会出现此异常。

════════ Exception caught by provider ══════════════════════════════════════════
The following assertion was thrown:
An exception was throw by _MapStream<DocumentSnapshot<Map<String, dynamic>>, UserProfileModel> listened by

StreamProvider<UserProfileModel?>, but no `catchError` was provided.

Exception:
Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist

════════════════════════════════════════════════════════════════════════════════

我认为这是因为开始时的 userId 为空,因此,它给出了这个异常。它不会导致崩溃或错误,但我不希望异常显示在调试控制台中。 这是 userProfileData 代码

Stream<UserProfileModel> userProfileData(String? user) {
    return _firestore
        .collection('users')
        .doc(user)
        .collection('userProfile')
        .doc(user)
        .snapshots()
        .map(_userProfileDataFromSnapshot);
  }

任何帮助将不胜感激。

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    如您上面提供的错误所示,这意味着 StreamProvider 具有名为 catchError 的属性,该属性是处理发出的错误并在发生错误时提供回退所必需的。

    要捕获null,您可以检查以下示例中的方法。

    StreamProvider(
      ...
      catchError: (_, __) => null,
      ...
    )
    

    您也可以参考此documentation 了解更多信息。

    【讨论】:

    • 谢谢,这消除了异常。但我不确定这是否是我必须添加的全部内容?
    • 嗨@user16017178,如果问题只是删除异常,则无需添加到给定答案。您始终可以浏览答案中提供的文档并使用对您有用/有用的适当属性。
    猜你喜欢
    • 2021-05-16
    • 2023-01-11
    • 2021-10-26
    • 2021-06-17
    • 2021-05-19
    • 2021-04-27
    • 1970-01-01
    • 2021-03-20
    • 2021-08-15
    相关资源
    最近更新 更多