控件不会进入颤振循环

Control doesn't enter the loop in flutter

我有一个课程类型的列表。我正在使用提供程序将值添加到列表中。在尝试将数据存储在地图中时,控件不会进入循环。我想知道是什么让控件跳出循环。非常感谢任何帮助。提前致谢!

我有一个课程模型 class,

class Course {
  List<Map<String, List<String>>> list;
  Course(this.list);
}

内部提供商 class、

  List<Course> _list = [];

  List<Course> get values => _list;

  void addValues(String coursename, String newValue) {
    // ! Control doesn't enter the loop
    values.map((course) {
      print('inside values.map');
      course.list.map((element) {
        element['$coursename'] = ['$newValue'];
        print('added map : $element');
      });
    }).toList();
    notifyListeners();
  }


调用 addValues

void clicked(String courseName, String newValue, BuildContext context) {
    if (newValue != null) {
      Provider.of<CourseProvider>(context, listen: false)
          .addValues(courseName, newValue);
    } 
    Navigator.pop(context);
  }

供参考的虚拟列表:

 List<Course> _list = [
    Course(
      list: [
       {
        'Morning_0': ['aaa', 'bbb', 'ccc', 'ddd']
      },
      {
        'Evening_0': ['eee', 'fff', 'ggg']
      },
      ],
    ), //1
  ];


使用 map 函数遍历列表来修改其内容很容易出错,应该避免。 它还会为每个 toList() 调用创建新的列表实例这不是你想要的。您应该为您的用例使用标准循环方法,例如 forEachfor 循环。以下是可用于 dart 语言的标准循环机制。

  1. forEach
  2. for循环
  3. 同时
  4. 同时做

查看 more details 的语言导览。


好吧,你警告得够多了,现在在这里我解释一下你的代码不起作用的技术原因。

有两个原因。

  1. 如果_list最初为空,则不会调用第一个map函数。所以在使用map函数之前需要确保你的list不为空
  2. 您忘记在 course.list.map
  3. 上致电 toList()

As long as the returned Iterable is not iterated over, the supplied function will not be invoked.

查看下面的编辑片段

 values.map((course) {
  print('inside values.map');
  course.list.map((element) {
    element['$coursename'] = ['$newValue'];
    print('added map : $element');
  }).toList();
}).toList();