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


Asked by user16017178 on November 27, 2021 (source).

I've a provider stream setup on MyApp.

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

  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 =<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(),

This gets userType from database and shows the screen accordingly, it works fine but whenever i run the app it gives this exception.

════════ 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.

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


I figured it's because the userId at start is null and due to this, it gives this exception. It causes no crash or bugs, but i don't want the Exception to be showing in Debug console. Here is the userProfileData code

Stream<UserProfileModel> userProfileData(String? user) {
    return _firestore

Any help will be appreciated.


Question answered by Marc A (source).

As shown in the error you provided above, it means that StreamProvider has property called catchError which is required to handle errors emitted and also provide fallback in case of errors.

To catch null, you could check the approach like in example below.

  catchError: (_, __) => null,

You could also refer this documentation for more information.