0

I have a list of String addresses like:

List<String> addressStrings = [....];

I am using the geocoding plugin to get the address data and marker for these address strings:

//This is a class-level function
Future<List<MarkerData>> getMarkerDataList() async {
  List<MarkerData> list = [];
  addressStrings.forEach((element) async {
    final result = await locationFromAddress(element);
    final markerData = MarkerData(element, result.first);

    list.add(markerData);
});

  return list;
}

But it freezes the UI as expected. I tried to use compute to perform the operation in another isolate like:

//This is a top-level function
Future<List<MarkerData>> getMarkerDataList(List<String> addressStrings) async {
  List<MarkerData> list = [];
  addressStrings.forEach((element) async {
    final result = await locationFromAddress(element);
    final markerData = MarkerData(element, result.first);

    list.add(markerData);
});

  return list;
}



//This is a class-level function
Future<List<MarkerData>> getMarkerData()async{
  final result = await compute(getMarkerDataList, addressStrings);
  return result;
}

But it doesn't work and shows an Unhandled exception in the console.

I guess the final result = await locationFromAddress(element); request is the problem. Because it does pass before that statement but doesn't this one.

So, my question is: does compute support async? If yes, what am I doing wrong here? If not, how can I do asynchronous performance-intensive tasks like this efficiently without blocking the UI?

S. M. JAHANGIR
  • 4,324
  • 1
  • 10
  • 30
  • If a Future freezes your UI, you have a bug in your UI. You may want to post your UI code. The whole point of a Future is to make it possible to do things without freezing others. – nvoigt Jul 09 '21 at 07:49
  • Obviously @pskink meant `for (var a in addressStrings) { ...`. Anyway, see https://stackoverflow.com/a/63719805/. I suspect your UI isn't "freezing" but that you're misinterpreting what happens when your UI is built with no data (due incorrectly attempting to use an `async` callback with `Iterable.forEach`). Or, as @nvoight suggested, your UI is simply broken if there's no loaded data. – jamesdlin Jul 09 '21 at 09:09

1 Answers1

0

Yes, as far as I know async does support compute - here's an article that should help out:

https://medium.com/flutterdevs/flutter-performance-optimization-17c99bb31553

Brady
  • 869
  • 8
  • 8