将数据从Firestore加载到带有抖动的列表中的问题

时间:2019-05-09 09:58:26

标签: firebase dart flutter google-cloud-firestore

Firestore文档包含特定的用户信息(用户名,年龄,挑战等)。当然,一个用户可能面临多个挑战。我正在将特定的用户数据加载到对象列表中,但是当我将该列表返回给FutureBuilder时会出现问题。假设我有2个用户,每个用户都有3个挑战。当我返回列表时,它显示正确的长度(6),但仅包含来自加载到列表中的最后一个用户的数据。我的ListView.builder显示6个_cardBuilder,但这些卡中的数据相同。

我试图用Map列表代替构造函数列表,但是结果是一样的。这可能是一个逻辑错误,但我找不到它。

Future<List<AllChallengesStorage>> challengesToFeed () async {

    var queryResult = await Firestore.instance.collection("Users")
        .where("total_challenges", isGreaterThanOrEqualTo: 1)
        .getDocuments();

    if (queryResult.documents.isNotEmpty){  

      for (int i=0; i < queryResult.documents.length; ++i){
        for (int j=0; j < queryResult.documents[i].data['total_challenges']; ++j){

          widget.challengesInfo.username = queryResult.documents[i].data['username'];
          widget.challengesInfo.name = queryResult.documents[i].data['challenges'][j]['name'];
          widget.challengesInfo.description = queryResult.documents[i].data['challenges'][j]['description'];
          widget.challengesInfo.duration = queryResult.documents[i].data['challenges'][j]['duration'];

          allChallenges.add(widget.challengesInfo);
        }
      }
    }
    return allChallenges;
  }


class _FeedState extends State<Feed> {

  List<AllChallengesStorage> allChallenges = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<AllChallengesStorage>>(
        future: challengesToFeed(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData) return Center(child: Text("Loading..."));
          return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (BuildContext context, int index) {
              return _cardBuilder(context, snapshot, index);
            },
          );
        },
      ),
    );
  }

1 个答案:

答案 0 :(得分:0)

问题是您正在使用同一对象,并且在每个循环上都覆盖了它的属性。您需要为每张新卡实例化一个新对象,例如,每当第二次循环完成时,使用模型类创建一个新的帮助对象。

    for (int i=0; i < queryResult.documents.length; ++i){
       ClassName helper = ClassName();
    for (int j=0; j < queryResult.documents[i].data['total_challenges']; ++j){

      helper.username = queryResult.documents[i].data['username'];
      helper.name = queryResult.documents[i].data['challenges'][j]['name'];
      helper.description = queryResult.documents[i].data['challenges'][j]['description'];
      helper.duration = queryResult.documents[i].data['challenges'][j]['duration'];

      allChallenges.add(helper);
    }
  }
}

然后访问列表中的对象,您可以指定索引并访问该索引处的对象及其属性

allChallenges[index].name