0

慢慢掌握 Flutter 和 Dart 作为我的新爱好。您可以提供的任何建议或帮助将不胜感激!我正在尝试实现一个简单的朋友系统,您可以在其中搜索另一个用户并将他们添加为朋友。

预期的结果是:

  1. 登录用户转到朋友的个人资料并单击“添加朋友”按钮。
  2. Firestore 有一个 users 集合。在该集合中是包含个人资料信息的每个用户的文档,包括数组“朋友”。单击“添加朋友”按钮会将登录的用户 UID 添加到第二个人的“朋友”数组中。
  3. 然后在好友屏幕上,我使用 StreamBuilder 和 Listview.builder 将所有用户显示为卡片,这些用户的“好友”数组中有登录用户的 UID。

为此,我想使用.where('friends', arrayContains: 'user.uid'),仅在屏幕列表中显示这些用户卡。

这是我写的代码:

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

    return 
      StreamBuilder(
      stream: Firestore.instance
              .collection('users')
              .where('friends', arrayContains: user.uid).snapshots(),
               builder: (context, documents) {

               if (documents.hasData) {
               return 

               Container(
                    height: 180,
                        child:

                            ListView.builder(
                               scrollDirection: Axis.horizontal,
                               itemCount: 1,
                               itemBuilder: (context, index) {

                               DocumentSnapshot friends = documents.data.documents[index]; 

但是,当我运行我的应用程序时,它显示错误:

`The following RangeError was thrown building:
      RangeError (index): Invalid value: Valid value range is empty: 0

      When the exception was thrown, this was the stack 
        List.[](dart:core-patch/growable_array.dart:149:60)
        friendsList.build.<anonymous closure>.<anonymous closure> 

笔记:

  1. itemCount 现在被硬编码为 1。我只希望在测试时返回 1 个用户。一旦一切正常,我将在 Firestore 中填充更多用户。
  2. 当我将 arrayContains 换成 .where ('displayName', isEqualTo: 'My Name').snapshots(),之类的更简单的东西时,应用程序可以正常工作
  3. user.uid 已经过测试并且确实包含预期的字符串
  4. 数组在 Firestore 中存在值(请参阅帖子底部的链接)
  5. 我已经为我在“用户”中使用的值设置了一个索引

有谁知道我可以对这个错误做些什么并检索具有登录用户 UID 的朋友数组的文档?

再次感谢任何建议和帮助。 Cloud Firestore 的屏幕截图在这里

4

2 回答 2

1

我离开了我的项目两天,并在最后一个小时内重建了应用程序。令我惊讶的是,'.where('friends', arrayContains: user.uid)' 现在可以工作了!

当应用程序启动时,我现在有一个包含当前登录用户的朋友的所有用户的 ListView。

完整系统的工作原理:

  1. 在每个用户的个人资料页面上都有一个浮动操作按钮,按下该按钮时,会将当前登录用户的 UID 添加到该朋友文档中的“朋友”数组中。

  2. 使用 StreamBuilder 和 ListView,当登录用户然后转到他们的朋友页面时,他们会在他们的“朋友”数组中看到每个具有登录用户 UID 的用户

于 2020-03-14T14:09:41.073 回答
0

可能是您正在从 firebase 打印空数据的结果。

Stream<List<Model>> fetchStream({@required String userUID}) {
return nestsCollection
    .where("participants", arrayContains: userUID)
    .snapshots()
    .map((snapshot) {
    // print(snapshot.docs[0].data()['nestName']);
  return snapshot.docs
      .map((document) => Model.fromFirestore(document))
      .toList();
 });
}
于 2020-11-14T14:41:58.333 回答