flutter 我可以使用List.generate根据某些条件给予值吗?

c9x0cxw0  于 2023-06-07  发布在  Flutter
关注(0)|答案(2)|浏览(153)

我使用List. generate生成一个Map列表(List<Map<dynamic,dynamic>>)。我想在每个map中放置一个键“Type”,并根据列表中map的索引为其分配3个值“A”,“B”或“C”中的一个(例如,索引范围为0到3的map获得“Type”:“A”等等)。有没有一种方法可以使用List.generate来做这样的事情?

final List<Map<dynamic, dynamic>> flashcards = List.generate(10, (index) => {
  "isSelected": false,
  "id": index,
  "front": "front $index",
  "back": "back $index",
  "reviewDate": DateTime.now(),
  "answerStreak": 0,
  });
d8tt03nd

d8tt03nd1#

如果你在List.generate中打开回调函数,你可以执行多行操作(通过删除箭头函数声明),你可以执行任意多个if语句。例如下面的示例,扩展了num类以包含2种类型的in between函数,从而使if语句更简洁

final List<Map<dynamic, dynamic>> flashcards = List.generate(10, (index) {
    if (index.isBetweenInclusive(0, 3)) {
        return {
            "isSelected": false,
            "id": index,
            "front": "front $index",
            "back": "back $index",
            "reviewDate": DateTime.now(),
            "answerStreak": 0,
        };
    } else if (index.isBetweenInclusive(4, 7)) {
        return {
            "isSelected": false,
            "id": index,
            "front": "front $index",
            "back": "back $index",
            "reviewDate": DateTime.now(),
            "answerStreak": 0,
        };
    } else {
        return {
            "isSelected": false,
            "id": index,
            "front": "front $index",
            "back": "back $index",
            "reviewDate": DateTime.now(),
            "answerStreak": 0,
        };
    }
});

extension Range on num {
  bool isBetween(num from, num to) {
    return from < this && this < to;
  }
}

extension Range on num {
  bool isBetweenInclusive(num from, num to) {
    return from <= this && this <= to;
  }
}
8ehkhllq

8ehkhllq2#

试试这个

const abc = ["A", "B", "C"];
void main() {
  final List<Map<dynamic, dynamic>> flashcards = List.generate(
      10,
      (index) => {
            "isSelected": false,
            "id": index,
            "front": "front $index",
            "back": "back $index",
            "reviewDate": DateTime.now(),
            "answerStreak": 0,
            "Type": abc[index ~/ 4]
          });
}

相关问题