繁体   English   中英

如何从 Firestore 数据库中检索字符串数组并显示它 - flutter

[英]how to retrieve an array of strings from Firestore database and display it - flutter

这个想法是我试图在我的 flutter 应用程序的容器内显示“挑战规则”,我能够获得所有挑战信息,例如名称、描述和其他信息。

首先看看我的数据库和包含挑战的集合:

在此处输入图像描述

“规则”是我要检索的数组,

这是获取 function 的数据:

 List _challenges = [];

  fetchChallengeData() async {
    var _fireStoreInstance = FirebaseFirestore.instance;
    QuerySnapshot qn = await _fireStoreInstance.collection("challenges").get();

    setState(() {
      for (int i = 0; i < qn.docs.length; i++) {
        _challenges.add({
          "image-path": qn.docs[i]["image-path"],
          "description": qn.docs[i]["description"],
          "name": qn.docs[i]["name"],
          "date": qn.docs[i]["date"],
          "isTeam": qn.docs[i]["isTeam"],
          "price": qn.docs[i]["price"],
          "prize": qn.docs[i]["prize"],
        });
      }
    });
  }

如您所见,function 正在迭代集合内的文档(挑战),每个文档都有上面显示的数据,并将其添加到代码中声明的列表中。

现在获取数据后,我会将其传递到另一个屏幕并在此 function 中显示规则:

challengeRules(String title, String desc) {
    return Column(
      children: [
        Container(
          width: MediaQuery.of(context).size.width,
          color: Colors.purple,
          height: 35,
          child: Center(
              child: Text(
            title,
            style: TextStyle(
                color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
          )),
        ),
        Container(
          padding: EdgeInsets.all(15),
          width: MediaQuery.of(context).size.width,
          child: Directionality(
            textDirection: TextDirection.rtl,
            child: Text(
              desc,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 14, height: 1.8, letterSpacing: 1),
            ),
          ),
        ),
      ],
    );
  }

当我显示我获取的任何数据时,我使用例如widget._challenges['name']并且它正常显示数据,在最后一个代码中,“desc”是保存数组值的变量。

所以我的问题是,如何通过正在使用的获取 function 获取数组信息,以及如何显示和渲染数组数据?感谢您的帮助。

那么规则看起来就像一个字符串列表,所以类似于你的其他字段:

add({ 
   ...
   "prize" ... etc,
   // Create a list of strings from the rules key and fallback to an empty list when that doesn't exist.
   "rules": List<String>.from(qn.docs[i]["rules"] ?? []),
});

然后显示它们,例如:

Widget challengeRules(String title, String description, List<String> rules) {
   return Column(
     children: [
       Text(title),
       Text(description),
       // [...] is the spread operator that combines the lists 
       // [.map] iterates over every item in the list and returns a text widget
       ...rules.map((rule) => Text(rule)).toList(),
     ],
   );
}

我强烈建议为您的 Firestore 文档使用支持模型。 这样您的呼叫站点可以看起来更像这样:

final db = FirebaseFirestore.instance;
QuerySnapshot snapshot = await db.collection("challenges").get();

setState(() {
    challenges = snapshot.docs.map((doc) => Challenge.fromMap(doc)).toList();
});

挑战 model 是 class 看起来像您的 Firestore 文档

class Challenge {
    Challenge({required this.image, required this.path, required this.isTeam ... etc.});

    String image;
    String path;
    String isTeam;
    ... etc.

   static Challenge fromMap(Map<String, dynamic> data){
      return Challenge(
          image: data['image'],
          path: data['path'],
          isTeam: data['isTeam'],
          ... etc.
      );
   }
}

然后只是传递您的挑战 model ,例如:

Widget challengeRules(Challenge challenge) {
   return Column(
     children: [
       Text(challenge.title),
       Text(challenge.description),
       ...challenge.rules.map((rule) => Text(rule)).toList(),
     ],
   );
}

我还建议将该方法转换为无状态小部件: https://api.flutter.dev/flutter/widgets/StatelessWidget-class.html

...
child: ChallengeViewWidget(challenge: challenge),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM