【问题标题】:Flutter List<DocumentSnapshot> not getting all valuesFlutter List<DocumentSnapshot> 未获取所有值
【发布时间】:2019-08-06 16:25:36
【问题描述】:

我有一个 FutureBuilder(很高兴能够加载)从 Firebase 获取我的 DocumentSnapshot 列表,但问题是如果我按下/弹出屏幕,它会一遍又一遍地重建它。为了解决这个问题,我终于把它放在了initState,但我有一个问题,有时我没有从中获取所有文件。

我有一个按钮可以启用和禁用国家/地区过滤器,每次按下它几乎都会立即显示我的文档,例如我总共有 11 个和 5 个已过滤但有时我不会全部得到它们,直到得到我得到的值应用程序错误(_userList? 的长度)。我试图放置一个 Future 来强制等待,但我做不到,请指教。

var _userList;

_fetchUserList() {
    Future<QuerySnapshot> snapshot;
    if (_countryFilter) {
      //print('COUNTRY FILTER');
      snapshot = Firestore.instance.collection('u').where('country', isEqualTo: country).getDocuments();
    } else {
      //print('ALL FILTER');
      snapshot = Firestore.instance.collection('u').getDocuments();
    }
    snapshot.then((QuerySnapshot result) {
      final List<DocumentSnapshot> documents = result.documents;
      if (documents.length > 0) {
        final List<DocumentSnapshot> availableUsers =
            documents.where((DocumentSnapshot documentSnapshot) => documentSnapshot['userId'] != _id).toList();
        //print('userList Size: ' + availableUsers.length.toString());

        List<DocumentSnapshot> userShuffle = _shuffle(availableUsers);
        setState(() {
          _userList = userShuffle;
        });
      }
    });
  }

这是我的 GridView:

GridView.builder(
                    padding: const EdgeInsets.all(10.0),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2, mainAxisSpacing: 10.0, crossAxisSpacing: 10.0, childAspectRatio: 0.85),
                    itemBuilder: (context, index) {
                      return _buildItem(context, _userList[index]);
                    },
                    itemCount: _userList.length,
                  )

按钮:

onPressed: () async {
            if (_countryFilter) {
              _countryFilter = false;
            } else {
              _countryFilter = true;
            }
            await _fetchUserList();
            setState(() {});
          },

【问题讨论】:

  • 你是否从你的 _fetchUserList() 中返回一个承诺/未来;打电话?
  • 不,因为如果我把它放在 initState 上,我不能让它在未来构建器上工作,如果你能帮助我非常感激。它必须处于初始化状态,否则每次都会刷新

标签: android firebase flutter dart google-cloud-firestore


【解决方案1】:

我已经设法通过一些验证使其工作。不同用户长度的问题也是因为 buildItem 上也使用了“国家”变量。

Future _fetchUserList() async {
    setState(() {
      _userList = null;
      _userLenght = null;
    });
    QuerySnapshot snapshot;
    if (_countryFilter) {
      snapshot = await Firestore.instance.collection('u').where('country', isEqualTo: _myCountry).getDocuments();
    } else {
      snapshot = await Firestore.instance.collection('u').getDocuments();
    }

    final List<DocumentSnapshot> documents = snapshot.documents;
    if (documents.length > 0) {
      final List<DocumentSnapshot> availableUsers =
          documents.where((DocumentSnapshot documentSnapshot) => documentSnapshot['userId'] != _id).toList();
      _userLenght = availableUsers.length;

      if (_userLenght > 0) {
        List<DocumentSnapshot> userShuffle = _shuffle(availableUsers);
        _userList = userShuffle;
      }
      setState(() {});
    }
  }
(_userList == null && _userLenght == null)
                      ? Container(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: <Widget>[
                              Center(
                                child: Container(
                                  width: 50.0,
                                  height: 50.0,
                                  alignment: Alignment.center,
                                  child: CircularProgressIndicator(
                                    valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor),
                                    strokeWidth: 2.0,
                                  ),
                                ),
                              ),
                              SizedBox(height: 12.0),
                              Text(
                                "We are loading the users",
                                style: TextStyle(
                                  color: Colors.black54,
                                  fontWeight: FontWeight.bold,
                                ),
                                textAlign: TextAlign.center,
                              ),
                            ],
                          ),
                        )
                      : (_userLenght == 0)
                          ? Container(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: <Widget>[
                                  Center(
                                    child: Icon(
                                      Icons.supervisor_account,
                                      color: Theme.of(context).primaryColor.withOpacity(0.8),
                                      size: 50.0,
                                    ),
                                  ),
                                  SizedBox(height: 12.0),
                                  Text(
                                    "No one was found\nTry reloading the screen",
                                    style: TextStyle(
                                      color: Colors.black54,
                                      fontWeight: FontWeight.bold,
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                ],
                              ),
                            )
                          : GridView.builder(
                              padding: const EdgeInsets.all(10.0),
                              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 2,
                                  mainAxisSpacing: 10.0,
                                  crossAxisSpacing: 10.0,
                                  childAspectRatio: 0.85),
                              itemBuilder: (context, index) {
                                return _buildItem(context, _userList[index]);
                              },
                              itemCount: _userLenght,
                            ),

希望这对某人有所帮助。有了这个,我每次推送和弹出屏幕时都能够停止屏幕用户列表随机播放,因为它仅在 initState 和 Button 上。

【讨论】:

    猜你喜欢
    • 2023-01-25
    • 1970-01-01
    • 2021-06-22
    • 2020-09-03
    • 2021-11-11
    • 2020-09-26
    • 2018-07-07
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多