从流颤振中返回 DocumentSnapshot<Map<String, dynamic>>>

问题描述

如果有人能帮助我发现 Flutter 应用程序中出现此错误的原因,我将不胜感激。

我认为是从数据库Stream返回的数据类型有问题

在我的应用程序中,我必须从 Firestore 的“用户”集合中检索用户信息以显示用户配置文件屏幕中,但我收到此错误

======== Exception caught by widgets library =======================================================
The following StateError was thrown building UserProfile(dirty,dependencies: [MediaQuery]):
Bad state: cannot get a field on a DocumentSnapshotPlatform that does not exist

The relevant error-causing widget was: 
  UserProfile file:///Users/JamesMontes/Documents/Flutter-projects/theloudculture/lib/pages/settings/settings_page.dart:30:28
When the exception was thrown,this was the stack: 
#0      DocumentSnapshotPlatform.get (package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:76:7)
#1      _JsonDocumentSnapshot.get (package:cloud_firestore/src/document_snapshot.dart:92:48)
#2      _JsonDocumentSnapshot.[] (package:cloud_firestore/src/document_snapshot.dart:96:40)
#3      UserProfile.build (package:theloudculture/pages/account/user_profile.dart:31:42)
#4      StatelessElement.build (package:Flutter/src/widgets/framework.dart:4569:28)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
Bad state: cannot get a field on a DocumentSnapshotPlatform that does not exist
The relevant error-causing widget was: 
  UserProfile file:///Users/JamesMontes/Documents/Flutter-projects/theloudculture/lib/pages/settings/settings_page.dart:30:28
====================================================================================================

======== Exception caught by widgets library =======================================================
Bad state: cannot get a field on a DocumentSnapshotPlatform that does not exist
The relevant error-causing widget was: 
  UserProfile file:///Users/JamesMontes/Documents/Flutter-projects/theloudculture/lib/pages/settings/settings_page.dart:30:28
====================================================================================================

我的文件有这个代码

database.dart(我检索用户数据的地方)

class DatabaseService {
  final String uid;

  DatabaseService({this.uid});

  // Get User stream
  Stream<DocumentSnapshot<Map<String,dynamic>>> get user {
    return usersCollection.doc(uid).snapshots();
  }
}

提供流的小部件是我的主页小部件并具有以下代码

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:Flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:theloudculture/models/user_model.dart';
import 'package:theloudculture/pages/inner_pages.dart';
import 'package:theloudculture/services/database.dart';
import 'package:theloudculture/widgets/widgets.dart';

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = Provider.of<CustomUser>(context);

    return StreamProvider<DocumentSnapshot<Map<String,dynamic>>>.value(
      value: DatabaseService(uid: user != null ? user.uid : null).user,child: ChangeNotifierProvider(
        create: (_) => NavegacionModel(),child: Container(
          color: Colors.black,child: Scaffold(
            backgroundColor: Colors.black,appBar: LoudAppBar(),body: Paginas(),bottomNavigationBar: BottomNavBar(),),);
  }
}

class NavegacionModel with ChangeNotifier {
  int _paginaActual = 0;
  int get paginaActual => this._paginaActual;

  set paginaActual(int valor) {
    this._paginaActual = valor;

    //Notifying widgets
    notifyListeners();
  }
}

settings_page 是 home 小部件的子级,所以我从那个小部件访问 userData

import 'package:animate_do/animate_do.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:Flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:theloudculture/pages/account/user_profile.dart';
import 'package:theloudculture/services/auth.dart';
import 'package:theloudculture/shared/loading.dart';
import 'package:theloudculture/widgets/widgets.dart';

class SettingsPage extends StatelessWidget {
  final AuthService _auth = AuthService();

  @override
  Widget build(BuildContext context) {
    final userData =
        Provider.of<DocumentSnapshot<Map<String,dynamic>>>(context);

    print(userData);

    return userData == null
        ? Loading()
        : FadeIn(
            duration: Duration(milliseconds: 500),child: Container(
              padding: EdgeInsets.symmetric(horizontal: 10.0),child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,children: <Widget>[
                  Expanded(
                    child: UserProfile(userData: userData),LargeBtn(
                    btnText: 'Salir',bottomMargin: true,btnAction: () async {
                      await _auth.signOut();
                    },],);
  }
}

此外,错误提到了 UserProfile 小部件,这是代码

import 'package:Flutter/material.dart';
import 'package:theloudculture/pages/account/user_edit_page.dart';
import 'package:theloudculture/pages/account/user_profile_header.dart';
import 'package:theloudculture/shared/loading.dart';
import 'package:theloudculture/widgets/outlined_custom_button.dart';

class UserProfile extends StatelessWidget {
  final userData;

  const UserProfile({
    Key key,this.userData,}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return userData == null
        ? Loading()
        : Container(
            width: screenSize.width * 0.95,height: screenSize.height * 0.7,padding: EdgeInsets.only(top: 15.0),child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,children: <Widget>[
                userData == null
                    ? Loading()
                    : UserProfileHeader(
                        userUid: userData['userUid'],userReferrerCode: userData['userReferrerCode'],firstName: userData['firstName'],lastName: userData['lastName'],displayName: userData['displayName'],email: userData['email'],actualProfileImageName: userData['profileImageName'],profileImageUrl: userData['profileImageUrl'],Container(
                  padding: EdgeInsets.only(top: 15.0),child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
                          Text('Amigos Invitados:'),SizedBox(width: 10.0),Text(userData['invitedFriends'].toString()),SizedBox(height: 20.0),OutlinedCustomButton(
                        btnText: 'Editar Perfil',btnAction: () {
                          Navigator.push(
                            context,MaterialPageRoute(
                              builder: (context) => UserEditPage(),);
                        },Expanded(
                  child: Container(
                    padding:
                        EdgeInsets.symmetric(vertical: 10.0,horizontal: 10.0),child: Center(
                      child: Text(
                        'Aquí van las opciones',style: TextStyle(color: Colors.white),)
              ],);
  }
}

解决方法

由于无法发表评论,因此我将其作为答案发布。您的日志中明确指出 错误状态:无法在不存在的 DocumentSnapshotPlatform 上获取字段。您要提取的字段之一在您的数据库中不存在。

替换

    Stream<DocumentSnapshot<Map<String,dynamic>>> get user {
       return usersCollection.doc(uid).snapshots();
    }

    Stream<DocumentSnapshot<Map<String,dynamic>>> get user {
       return FirebaseFirestore.instance.collection('users').where('uid',isEqualTo: uid).snapshots();
    }