Dart / Flutter:在继续之前等待循环完成......(异步等待?)

时间:2021-04-07 08:01:59

标签: flutter loops dart asynchronous async-await

我有一个函数可以从一个大(非常大的列表)中创建一个子列表。创建此列表后,该函数继续对其进行处理(删除重复项、排序...)。

只要列表不是太大,它就可以正常工作。但是现在,我得到“Getter 长度被调用为空”。我想,这是因为函数的第二部分(循环之后)在子列表完成之前开始......所以它不起作用......

我们如何强制函数等待循环结束以继续其余的处理? 是使用 Async /Await 吗?或者我们可以做一些类似“虽然......事情还没有结束......”或“一旦某事完成......就这样做”? (我的建议可能很幼稚,但我是初学者...)

代码如下:

List themeBankFr() {
  List<Map> themeBankFr = [];
  for (Word word in wordBank) {
    for (Thematique wordTheme in word.theme) {
      themeBankFr.add({
        'themeFr': wordTheme.themeFr,
        'image': wordTheme.image,
      });
    }
  }
// convert each item to a string by using JSON encoding
  final jsonList = themeBankFr.map((item) => jsonEncode(item)).toList();

  // using toSet - toList strategy
  final uniqueJsonList = jsonList.toSet().toList();

  // convert each item back to the original form using JSON decoding
  final result = uniqueJsonList.map((item) => jsonDecode(item)).toList();

  // sort the list of map in alphabetical order
  result.sort((m1, m2) {
    var r = m1['themeFr'].compareTo(m2['themeFr']);
    if (r != 0) return r;
    return m1['image'].compareTo(m2['image']);
  });

  return result;
}

1 个答案:

答案 0 :(得分:1)

我想我有一个很好的答案可以帮助你,它会如下

首先创建另一个函数来完成 for 循环的工作,该函数返回您需要的列表的未来,如下所示

Future<List<Map>> futureList(List wordBank){
  List<Map> themeBankFr = [];
  for (Word word in wordBank) {
    for (Thematique wordTheme in word.theme) {
      themeBankFr.add({
        'themeFr': wordTheme.themeFr,
        'image': wordTheme.image,
      });
    }
  }
  return Future.value(themeBankFr);
}

之后,您可以在代码中使用此函数并将其用作异步等待,现在您将永远不会在返回此数组之前运行以下行,如下所示

List themeBankFr() async {
  List<Map> themeBankFr = await futureList(wordBank);
// convert each item to a string by using JSON encoding
  final jsonList = themeBankFr.map((item) => jsonEncode(item)).toList();

  // using toSet - toList strategy
  final uniqueJsonList = jsonList.toSet().toList();

  // convert each item back to the original form using JSON decoding
  final result = uniqueJsonList.map((item) => jsonDecode(item)).toList();

  // sort the list of map in alphabetical order
  result.sort((m1, m2) {
    var r = m1['themeFr'].compareTo(m2['themeFr']);
    if (r != 0) return r;
    return m1['image'].compareTo(m2['image']);
  });

  return result;
}

我认为这将解决您的问题,希望对您有用