You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何从Firestore获取字符串数组并渲染展示?

解决Flutter中Firestore规则数组的获取与展示问题

1. 修改数据获取函数,添加rules数组获取

在fetchChallengeData函数的对象映射中,直接新增rules字段,从Firestore文档中取出数组即可(Firestore会自动将数组映射为Dart的List类型):

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"],
        "rules": qn.docs[i]["rules"], // 新增该行,获取rules数组
      });
    }
  });
}

2. 修改规则展示函数,渲染数组内容

将原challengeRules函数的参数从单个字符串改为List<String>类型的数组,然后遍历数组生成每条规则的展示条目,保留原有样式的同时适配数组内容:

Widget challengeRules(String title, List<String> rules) {
  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: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: List.generate(rules.length, (index) {
              // 遍历数组生成带序号的规则条目
              return Text(
                "${index + 1}. ${rules[index]}",
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 14, height: 1.8, letterSpacing: 1),
              );
            }),
          ),
        ),
      ),
    ],
  );
}

调用示例

传递数据时,直接将数组传入修改后的函数即可:

challengeRules(widget._challenges['name'], widget._challenges['rules']);

内容的提问来源于stack exchange,提问作者editix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 01:45:41