Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

flutter - Adding list depending on a variable

I want to add a list to another list. That's not hard, I did it with list = list + test1;, but the problem is that I want to add another list depending on a variable.

To give you an instance: if a String is test1, than I want to add the test1 list, if the variable is test2 than the test2 list and so on. I have the lists test1, test2, test3,... hardcoded (see below). I tried the code list = list + listVariable, but it doesn′t work.

listVariable is a String which can be changed by the user by a textfield. For example, when the user enters test2 in the textfield than the list test2 should be added to the list list. The problem is that I can′t hardcode it like if (listVariable == test2) {list = list + test2}, because I have too many lists. If I haven't described my issue good enough, please let me know.

That are my lists:

var test1 = [
  {"name": "test1.1", "time": 10},
  {"name": "test1.2", "time": 10},
];

var test2 = [
  {"name": "test2.1", "time": 10},
  {"name": "test2.2", "time": 10},
];
question from:https://stackoverflow.com/questions/65833070/adding-list-depending-on-a-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe you can try mapping the values like this:

    // INPUT FROM USER TEXT FIELD
    String listVariable;

    var list1 = [
      {"name": "test1.1", "time": 10},
      {"name": "test1.2", "time": 10},
    ];

    var list2 = [
      {"name": "test2.1", "time": 10},
      {"name": "test2.2", "time": 10},
    ];

    Map<String, List> map = {
      'test1': list1,
      'test2': list2,
    };

    if (map[listVariable] != null) {
      var list = list + map[listVariable];
    } else {
      print("User dont match any list values");
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...