【问题标题】:looping inside a list in dart flutter在飞镖颤动的列表中循环
【发布时间】:2021-12-18 02:20:21
【问题描述】:

我正在尝试从 firebase 检索列表,然后打印所有列表内容。 我尝试了经典的 for 循环,但它显示错误我猜我的方法不正确

这是我的代码

body: StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance
          .collection('Users')
          .doc("list_instructors")
          .collection('Instructor')
          .where('Email', isEqualTo: email)
          .snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return ListView.separated(
              itemCount: snapshot.data!.docs.length,
              separatorBuilder: (BuildContext context, int index) =>
                  Divider(height: 1),

              // ignore: dead_code
              itemBuilder: (context, int index) {
                DocumentSnapshot doc = snapshot.data!.docs[index];
                List courses = doc['Courses'];
                return ListTile(
                  contentPadding:
                      EdgeInsets.symmetric(horizontal: 30, vertical: 10),
                  selectedTileColor: Color(0xffE5E5E5),

                  title: Text(
                    for(i = 0; i < courses.length; i++) {
                     courses[i].toString() 
                    },
                    style: GoogleFonts.asap(
                      fontSize: 22,
                      color: const Color(0xff455e89),
                      fontWeight: FontWeight.w700,
                    ),
                    textAlign: TextAlign.left,
                  ),

这是我当前的输出,我只能从我的 firbase 列表中检索一个元素。

这是列表,我希望打印所有列表内容 没有for循环我该怎么做?

【问题讨论】:

  • 请编辑您的问题以显示您收到的错误消息。
  • 此外,如果您可以显示一些示例输出与一些预期输出,那么我在整理您希望上面的代码执行的操作时遇到了一些麻烦。它是否应该在 ListTile 中为特定教授教授的每门课程显示一个文本小部件?还是单个 ListTile 中的单个文本小部件,其中包含特定教授教授的所有课程?
  • 我刚刚更新了我的帖子,请检查一下。
  • 是的,每一门课程都由特定教授教授
  • 您可以尝试将List courses = doc['Courses']; 更改为List&lt;String&gt; courses = List.castFrom(doc['Courses'] as List ?? []);,如here 所述吗?

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

courses 似乎没有正确读取为List

代替这一行:

List courses = doc['Courses'];

试试这个:

var coursesListFromJson = json['Courses'];
List<String> courses = (coursesListFromJson != null) ? coursesListFromJson.cast<String>() : null;

【讨论】:

  • 当我尝试您的代码时,它显示此错误:未为类型“JsonCodec”定义运算符“[]”。尝试定义运算符“[]”。
猜你喜欢
  • 2021-01-24
  • 2020-08-12
  • 2020-02-11
  • 1970-01-01
  • 2018-05-25
  • 2022-06-19
  • 2019-12-29
  • 2020-10-22
  • 2019-02-20
相关资源
最近更新 更多