【问题标题】:How to update a map that has a list as values如何更新以列表为值的地图
【发布时间】:2020-11-25 18:05:07
【问题描述】:

我有一张Map<DateTime, List<dynamic>> 类型的地图。它的实例是这样的:

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

如何在列表值的一个位置更新这些键中的任何一个的值?这是我尝试过的:

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

但目前它给出以下错误:

错误:返回类型“字符串”不是闭包上下文所要求的“列表”

我该如何执行它,我如何设置我想要更新的列表的位置?在这种情况下,我只想更新用户触摸的值。

【问题讨论】:

  • 如果像 Test1 和 Test2 这样的东西实际上是字符串,或者是对未在 sn-p 中定义的对象的引用,您可能想要限定。
  • 只是字符串,但如果有2个相等,我必须只识别选定的
  • @ChristopherMoore,这是我尝试过的,但没有奏效。我的问题需要阅读。我知道错误很清楚,但我不知道该怎么做(写在问题中),所以,你可以告诉我们你的答案。如果你知道
  • 我不知道您的预期结果是什么。您必须提供更多详细信息才能获得完整的答案。
  • 我想更新一些值,例如,第一张地图中的值 0。这个值现在将是“test44444”。所以,现在我的地图是 2020-11-26:[Test44444, Test2, Test3, Test4]

标签: dictionary dart types


【解决方案1】:

使用docs 中的[]= 运算符

_myMap[_day][0] = Test44444;

完整样本:

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);
}

输出:

{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]}

【讨论】:

  • @TomBrady0fCode 如果您尝试这样做,它会更新值。
  • 如果这个更新我还有另一个问题,因为这里不是。我会检查
  • @TomBrady0fCode 我提供了一个完整的示例,显示此 更新 值。这不是添加操作。
【解决方案2】:

你可以做的一个例子:

//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]),
              );
            }),
          );
        },
      ),
    ),
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多