How to update a map that has a list as values

Viewed 112

I have a map of type Map<DateTime, List<dynamic>>. Its instances are like this:

2020-11-26: [Test1, Test2, Test3, Test4]
2020-11-22: [Test331, Test55, Test1, Test55]

How could I update the value of any of these keys in one position of the list values? This is what I've tried:

_myMap.update(_day, (value) => _mapFieldController.text.toString());

But currently it is giving the following error:

error: The return type 'String' isn't a 'List', as required by the closure's context

How could I perform it, and how could I set the position of the list that I want update? In this case I only want to update the value touched by the user.

2 Answers

Use the []= operator from the docs

_myMap[_day][0] = Test44444;

Full sample:

void main() {
  DateTime _day = DateTime.now();
  
  Map<DateTime, List<dynamic>> _myMap = {
    _day: ['Test1', 'Test2', 'Test3', 'Test4'],
    _day.add(Duration(seconds: 5)): ['Test331', 'Test55', 'Test1', 'Test55'],
  };
  print(_myMap);
  
  _myMap[_day][0] = 'Test44444';
  
  print(_myMap);
}

Output:

{2020-11-25 14:03:07.880: [1, 2, 3, 4], 2020-11-25 14:03:12.880: [2, 3, 5, 6]}
{2020-11-25 14:03:07.880: [4444, 2, 3, 4], 2020-11-25 14:03:12.880: [2, 3, 5, 6]}

An example of what you can do:

//the map with some random data
Map<int, List<dynamic>> map = {
  2020: ['test1', 'test2'],
  1: ['m', 'a', 'p'],
};

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: ListView.builder(
        itemCount: map.length,
        itemBuilder: (context, mapIndex) {
          //getting the current list with the current Index
          List currentList = map.values.toList()[mapIndex];

          return Column(
            children: List.generate(currentList.length, (listIndex) {

              return GestureDetector(
                onTap: () {
                  //updating the "tapped" value
                  currentList[listIndex] = 'newValue';
                  setState(() {});
                },
                child: Text(currentList[listIndex]),
              );
            }),
          );
        },
      ),
    ),
  );
}
Related