skip to Main Content

I’m generating a list of maps (List<Map<dynamic, dynamic>>) using List.generate. I wanted to put a key "Type" in each of the maps and assign it one of 3 values "A", "B" or "C" depending on the index of the map inside of the list (for example a map that has the index from the range 0 to 3 gets "Type": "A" and so on). Is there a way you can do such a thing using 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,
  });

2

Answers


  1. if you open up the callback function in List.generate you can perform multiline actions (by removing the arrow function declaration) and you can perform as many if statements you want. for example below, extended the num class to include 2 types of in between functions to make the if statements a bit cleaner

    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;
      }
    }
    
    Login or Signup to reply.
  2. Try this

    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]
              });
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search