(执行updateData时出错,NOT_FOUND:没有要更新的文档:

时间:2020-05-12 01:09:36

标签: firebase flutter google-cloud-firestore feed

我进入Feed屏幕时遇到此错误,您能告诉我什么吗? feedsScreen应该向我显示我关注的人的所有帖子,但是它并没有显示任何内容,只是空白屏幕,并且在控制台中出现错误。

这是错误

Error performing updateData, NOT_FOUND: No document to update: projects/flutter-instagram-clone-c2f63/databases/(default)/documents/users/euZNNwshi6C1GsDW3ONJ, null)

这是供稿屏幕代码

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:jobly10/models/post_model.dart';
import 'package:jobly10/models/user_data.dart';
import 'package:jobly10/models/user_model.dart';
import 'package:jobly10/services/database_service.dart';
import 'package:jobly10/utilities/constants.dart';
import 'package:jobly10/widgets/post_view.dart';
import 'package:provider/provider.dart';
import 'comments_screen.dart';
import 'edit_profile_screen.dart';

class ProfileScreen extends StatefulWidget {
  static final String id = 'profile_screen';
  final String currentUserId;
  final String userId;

  ProfileScreen({this.currentUserId, this.userId});

  @override
  _ProfileScreenState createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  bool _isFollowing = false;
  int _followerCount = 0;
  int _followingCount = 0;
  List<Post> _posts = [];
  int _displayPosts = 0; // 0 - grid, 1 - column
  User _profileUser;

  @override
  void initState() {
    super.initState();
    _setupIsFollowing();
    _setupFollowers();
    _setupFollowing();
    _setupPosts();
    _setupProfileUser();
  }

  _setupIsFollowing() async {
    bool isFollowingUser = await DatabaseService.isFollowingUser(
      currentUserId: widget.currentUserId,
      userId: widget.userId,
    );
    if (!mounted) return;
    setState(() {
      _isFollowing = isFollowingUser;
    });
  }

  _setupFollowers() async {
    int userFollowerCount = await DatabaseService.numFollowers(widget.userId);
    if (!mounted) return;
    setState(() {
      _followerCount = userFollowerCount;
    });
  }

  _setupFollowing() async {
    int userFollowingCount = await DatabaseService.numFollowing(widget.userId);
    if (!mounted) return;
    setState(() {
      _followingCount = userFollowingCount;
    });
  }

  _setupPosts() async {
    List<Post> posts = await DatabaseService.getUserPosts(widget.userId);
    if (!mounted) return;
    setState(() {
      _posts = posts;
    });
  }

  _setupProfileUser() async {
    User profileUser = await DatabaseService.getUserWithId(widget.userId);
    if (!mounted) return;
    setState(() {
      _profileUser = profileUser;
    });
  }

  _followOrUnfollow() {
    if (_isFollowing) {
      _unfollowUser();
    } else {
      _followUser();
    }
  }

  _unfollowUser() {
    DatabaseService.unfollowUser(
      currentUserId: widget.currentUserId,
      userId: widget.userId,
    );
    if (!mounted) return;
    setState(() {
      _isFollowing = false;
      _followerCount--;
    });
  }

  _followUser() {
    DatabaseService.followUser(
      currentUserId: widget.currentUserId,
      userId: widget.userId,
    );
    if (!mounted) return;
    setState(() {
      _isFollowing = true;
      _followerCount++;
    });
  }

  _displayButton(User user) {
    return user.id == Provider.of<UserData>(context).currentUserId
        ? Container(
            width: 200.0,
            child: FlatButton(
              onPressed: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) => EditProfileScreen(
                    user: user,
                  ),
                ),
              ),
              color: Colors.deepPurpleAccent,
              textColor: Colors.white,
              child: Text(
                'Editar Pefil',
                style: TextStyle(fontSize: 18.0, fontFamily: 'Varela'),
              ),
            ),
          )
        : Container(
            width: 200.0,
            child: FlatButton(
              onPressed: _followOrUnfollow,
              color: _isFollowing ? Colors.grey[200] : Colors.blue,
              textColor: _isFollowing ? Colors.black : Colors.white,
              child: Text(
                _isFollowing ? 'Unfollow' : 'Follow',
                style: TextStyle(fontSize: 18.0),
              ),
            ),
          );
  }

  _buildProfileInfo(User user) {
    return Column(
      children: <Widget>[
        Padding(
          padding: EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 0.0),
          child: Row(
            children: <Widget>[
              CircleAvatar(
                radius: 50.0,
                backgroundColor: Colors.grey,
                backgroundImage: user.profileImageUrl.isEmpty
                    ? AssetImage('assets/images/user.png')
                    : CachedNetworkImageProvider(user.profileImageUrl),
              ),
              Expanded(
                child: Column(
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Column(
                          children: <Widget>[
                            Text(
                              _posts.length.toString(),
                              style: TextStyle(
                                fontSize: 18.0,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            Text(
                              'posts',
                              style: TextStyle(color: Colors.black54),
                            ),
                          ],
                        ),
                        Column(
                          children: <Widget>[
                            Text(
                              _followerCount.toString(),
                              style: TextStyle(
                                fontSize: 18.0,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            Text(
                              'followers',
                              style: TextStyle(color: Colors.black54),
                            ),
                          ],
                        ),
                        Column(
                          children: <Widget>[
                            Text(
                              _followingCount.toString(),
                              style: TextStyle(
                                fontSize: 18.0,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            Text(
                              'following',
                              style: TextStyle(color: Colors.black54),
                            ),
                          ],
                        ),
                      ],
                    ),
                    _displayButton(user),
                  ],
                ),
              )
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 30.0, vertical: 10.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                user.nickname,
                style: TextStyle(
                  fontSize: 18.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 5.0),
              Container(
                height: 80.0,
                child: Text(
                  user.bio,
                  style: TextStyle(fontSize: 15.0),
                ),
              ),
              Divider(),
            ],
          ),
        ),
      ],
    );
  }

  _buildToggleButtons() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        IconButton(
          icon: Icon(Icons.grid_on),
          iconSize: 30.0,
          color: _displayPosts == 0
              ? Theme.of(context).primaryColor
              : Colors.grey[300],
          onPressed: () => setState(() {
            _displayPosts = 0;
          }),
        ),
        IconButton(
          icon: Icon(Icons.list),
          iconSize: 30.0,
          color: _displayPosts == 1
              ? Theme.of(context).primaryColor
              : Colors.grey[300],
          onPressed: () => setState(() {
            _displayPosts = 1;
          }),
        ),
      ],
    );
  }

  _buildTilePost(Post post) {
    return GridTile(
      child: GestureDetector(
        onTap: () => Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => CommentsScreen(
              post: post,
              likeCount: post.likeCount,
            ),
          ),
        ),
        child: Image(
          image: CachedNetworkImageProvider(post.imageUrl),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  _buildDisplayPosts() {
    if (_displayPosts == 0) {
      // Grid
      List<GridTile> tiles = [];
      _posts.forEach(
        (post) => tiles.add(_buildTilePost(post)),
      );
      return GridView.count(
        crossAxisCount: 3,
        childAspectRatio: 1.0,
        mainAxisSpacing: 2.0,
        crossAxisSpacing: 2.0,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        children: tiles,
      );
    } else {
      // Column
      List<PostView> postViews = [];
      _posts.forEach((post) {
        postViews.add(
          PostView(
            currentUserId: widget.currentUserId,
            post: post,
            author: _profileUser,
          ),
        );
      });
      return Column(children: postViews);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: FutureBuilder(
        future: usersRef.document(widget.userId).get(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          User user = User.fromDoc(snapshot.data);
          return ListView(
            children: <Widget>[
              _buildProfileInfo(user),
              _buildToggleButtons(),
              Divider(),
              _buildDisplayPosts(),
            ],
          );
        },
      ),
    );
  }
}

这是帖子查看小工具

import 'dart:async';
import 'package:animator/animator.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:jobly10/models/post_model.dart';
import 'package:jobly10/models/user_model.dart';
import 'package:jobly10/screens/comments_screen.dart';
import 'package:jobly10/screens/profile_screen.dart';
import 'package:jobly10/services/database_service.dart';

class PostView extends StatefulWidget {
  final String currentUserId;
  final Post post;
  final User author;

  PostView({this.currentUserId, this.post, this.author});

  @override
  _PostViewState createState() => _PostViewState();
}

class _PostViewState extends State<PostView> {
  int _likeCount = 0;
  bool _isLiked = false;
  bool _heartAnim = false;

  @override
  void initState() {
    super.initState();
    _likeCount = widget.post.likeCount;
    _initPostLiked();
  }

  @override
  void didUpdateWidget(PostView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.post.likeCount != widget.post.likeCount) {
      _likeCount = widget.post.likeCount;
    }
  }

  _initPostLiked() async {
    bool isLiked = await DatabaseService.didLikePost(
      currentUserId: widget.currentUserId,
      post: widget.post,
    );
    if (mounted) {
      setState(() {
        _isLiked = isLiked;
      });
    }
  }

  _likePost() {
    if (_isLiked) {
      // Unlike Post
      DatabaseService.unlikePost(
          currentUserId: widget.currentUserId, post: widget.post);
      setState(() {
        _isLiked = false;
        _likeCount = _likeCount - 1;
      });
    } else {
      // Like Post
      DatabaseService.likePost(
          currentUserId: widget.currentUserId, post: widget.post);
      setState(() {
        _heartAnim = true;
        _isLiked = true;
        _likeCount = _likeCount + 1;
      });
      Timer(Duration(milliseconds: 350), () {
        setState(() {
          _heartAnim = false;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        GestureDetector(
          onTap: () => Navigator.push(
            context,
            MaterialPageRoute(
              builder: (_) => ProfileScreen(
                currentUserId: widget.currentUserId,
                userId: widget.post.authorId,
              ),
            ),
          ),
          child: Container(
            padding: EdgeInsets.symmetric(
              horizontal: 16.0,
              vertical: 10.0,
            ),
            child: Row(
              children: <Widget>[
                CircleAvatar(
                  radius: 25.0,
                  backgroundColor: Colors.grey,
                  backgroundImage: widget.author.profileImageUrl.isEmpty
                      ? AssetImage('assets/images/user_placeholder.jpg')
                      : CachedNetworkImageProvider(
                          widget.author.profileImageUrl),
                ),
                SizedBox(width: 8.0),
                Text(
                  widget.author.nickname,
                  style: TextStyle(
                    fontSize: 18.0,
                    fontWeight: FontWeight.w600,
                  ),
                )
              ],
            ),
          ),
        ),
        GestureDetector(
          onDoubleTap: _likePost,
          child: Stack(
            alignment: Alignment.center,
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).size.width,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: CachedNetworkImageProvider(widget.post.imageUrl),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              _heartAnim
                  ? Animator(
                      duration: Duration(milliseconds: 300),
                      tween: Tween(begin: 0.5, end: 1.4),
                      curve: Curves.elasticOut,
                      builder: (anim) => Transform.scale(
                        scale: anim.value,
                        child: Icon(
                          Icons.favorite,
                          size: 100.0,
                          color: Colors.red[400],
                        ),
                      ),
                    )
                  : SizedBox.shrink(),
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                children: <Widget>[
                  IconButton(
                    icon: _isLiked
                        ? Icon(
                            Icons.favorite,
                            color: Colors.red,
                          )
                        : Icon(Icons.favorite_border),
                    iconSize: 30.0,
                    onPressed: _likePost,
                  ),
                  IconButton(
                    icon: Icon(Icons.comment),
                    iconSize: 30.0,
                    onPressed: () => Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (_) => CommentsScreen(
                          post: widget.post,
                          likeCount: _likeCount,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 12.0),
                child: Text(
                  '${_likeCount.toString()} likes',
                  style: TextStyle(
                    fontSize: 16.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              SizedBox(height: 4.0),
              Row(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(
                      left: 12.0,
                      right: 6.0,
                    ),
                    child: Text(
                      widget.author.nickname,
                      style: TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Expanded(
                    child: Text(
                      widget.post.caption,
                      style: TextStyle(
                        fontSize: 16.0,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 12.0),
            ],
          ),
        ),
      ],
    );
  }
}

这是数据库

  static Future<List<Post>> getFeedPosts(String userId) async {
    QuerySnapshot feedSnapshot = await feedsRef
        .document(userId)
        .collection('userFeed')
        .orderBy('timestamp', descending: true)
        .getDocuments();
    List<Post> posts =
        feedSnapshot.documents.map((doc) => Post.fromDoc(doc)).toList();
    return posts;
  }

This is the Post model

import 'package:cloud_firestore/cloud_firestore.dart';

class Post {
  final String id;
  final String imageUrl;
  final String caption;
  final int likeCount;
  final String authorId;
  final Timestamp timestamp;

  Post({
    this.id,
    this.imageUrl,
    this.caption,
    this.likeCount,
    this.authorId,
    this.timestamp,
  });

  factory Post.fromDoc(DocumentSnapshot doc) {
    return Post(
      id: doc.documentID,
      imageUrl: doc['imageUrl'],
      caption: doc['caption'],
      likeCount: doc['likeCount'],
      authorId: doc['authorId'],
      timestamp: doc['timestamp'],
    );
  }
}

日志

Performing hot reload...
Syncing files to device SM A305G...
Reloaded 0 of 989 libraries in 771ms.
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 0
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 1
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 0
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 1
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 0
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 1
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 0
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 1
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 0
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 1
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 0
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 1
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 0
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 1
I/flutter (21125): token: dlwF3XAN-IU:APA91bHppNO3Ku6EzTyl_cVJnCA6Vq9lZ3CxzzBw1BJ57eN9G_bEeVtKN6YOsBzMQ0xO6C3q4FOx0YmnPW8a7DDxpRZUrWndNQwc6SNH2ek2vw_DusdBfQuxKzbkt73wF5ksTn-ssmus
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 0
D/ViewRootImpl@16cc112[MainActivity](21125): ViewPostIme pointer 1
E/flutter (21125): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(Error performing updateData, NOT_FOUND: No document to update: projects/flutter-instagram-clone-c2f63/databases/(default)/documents/users/euZNNwshi6C1GsDW3ONJ, null)
E/flutter (21125): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (21125): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33)
E/flutter (21125): <asynchronous suspension>
E/flutter (21125): #2      MethodChannelDocumentReference.updateData (package:cloud_firestore_platform_interface/src/method_channel/method_channel_document_reference.dart:41:43)
E/flutter (21125): #3      DocumentReference.updateData (package:cloud_firestore/src/document_reference.dart:60:10)
E/flutter (21125): #4      ListChatScreenState.registerNotification.<anonymous closure> (package:jobly10/chat_implementation/ListChat_screen.dart:73:12)
E/flutter (21125): #5      _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter (21125): #6      _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (21125): #7      _FutureListener.handleValue (dart:async/future_impl.dart:139:18)
E/flutter (21125): #8      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:680:45)
E/flutter (21125): #9      Future._propagateToListeners (dart:async/future_impl.dart:709:32)
E/flutter (21125): #10     Future._completeWithValue (dart:async/future_impl.dart:524:5)
E/flutter (21125): #11     _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:32:15)
E/flutter (21125): #12     _completeOnAsyncReturn (dart:async-patch/async_patch.dart:290:13)
E/flutter (21125): #13     FirebaseMessaging.getToken (package:firebase_messaging/firebase_messaging.dart)
E/flutter (21125): <asynchronous suspension>
E/flutter (21125): #14     ListChatScreenState.registerNotification (package:jobly10/chat_implementation/ListChat_screen.dart:68:23)
E/flutter (21125): #15     ListChatScreenState.initState (package:jobly10/chat_implementation/ListChat_screen.dart:47:5)
E/flutter (21125): #16     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
E/flutter (21125): #17     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
E/flutter (21125): #18     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (21125): #19     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (21125): #20     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14)
E/flutter (21125): #21     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (21125): #22     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (21125): #23     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14)
E/flutter (21125): #24     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (21125): #25     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (21125): #26     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
E/flutter (21125): #27     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
E/flutter (21125): #28     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
E/flutter (21125): #29     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
E/flutter (21125): #30     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (21125): #31     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (21125): #32     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
E/flutter (21125): #33     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
E/flutter (21125): #34     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
E/flutter (21125): #35     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
E/flutter (21125): #36     ParentDataElement.mount (package:flutter/src/widgets/framework.dart:4617:11)
E/flutter (21125): #37     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (21125): #38     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (21125): #39     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
E/flutter (21125): #40     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
E/flutter (21125): #41     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
E/flutter (21125): #42     StatefulElement._firstBuild (package:flutter/src/widgets/framework.d

enter image description here

这是我在Firebase中的数据库

0 个答案:

没有答案