Yashwardhan Pauranik
Yashwardhan Pauranik

Reputation: 5556

Flutter compute function not compiling

I have a repository class (check below) that calls APIs through the HttpService class. I'm receiving historical data that contains 1000s of data objects. To avoid the computation problem, I'm trying to implement the compute() function to move this computation out of the main thread, but Android Studio is giving a compilation error.

class WealthRepo {

    Future<Responser<PerformanceHistoryModel>> fetchPortfolioHistory(
    String stackId,
    String? duration,
    ) async {
    try {
      final resp = await _httpService.makePostRequest(<API_EP>, jsonEncode(<REQUEST_OBJ>));

      return Responser<PerformanceHistoryModel>(
        message: '',
        isSuccess: true,
        data: compute(parsePerformanceHistory, resp),
      );
    } catch (e, st) {
      return ErrorHandler.error<PerformanceHistoryModel>(
        e,
        stackTrace: st,
      );
    }
  }
}

/// Outside WealthRepo class
PerformanceHistoryModel parsePerformanceHistory(Map<String, dynamic> response) {
  return PerformanceHistoryModel.fromJson(response);
}

lib/repositories/wealth_repo.dart:1431:23: Error: The argument type 'PerformanceHistoryModel Function(Map<String, dynamic>)' can't be assigned to the parameter type 'FutureOr Function(dynamic)'.

  • 'PerformanceHistoryModel' is from 'package:aphrodite_v2/data/models/wealth/performance_history_model.dart' ('lib/data/models/wealth/performance_history_model.dart').
  • 'Map' is from 'dart:core'. data: compute(parsePerformanceHistory, resp), ^

PS - Responser is a custom response class we created. Not sure how to resolve this issue.

class Responser<T> {
  final String message;
  final bool isSuccess;
  T? data;

  Responser({
    required this.message,
    required this.isSuccess,
    this.data,
  });

  @override
  String toString() =>
      'Responser(message: $message, isSuccess: $isSuccess, data: $data)';
}

enter image description here

Upvotes: 0

Views: 907

Answers (1)

Nico Spencer
Nico Spencer

Reputation: 1181

You either need to await your resp before passing it into the compute function.

      return Responser<PerformanceHistoryModel>(
        message: '',
        isSuccess: true,                       \/\/     
        data: compute(parsePerformanceHistory, await resp),
      );

Or you need to update the signature on the function that compute uses so that it takes in a FutureOr<Map<String, dynamic>>.

  Future<PerformanceHistoryModel> parsePerformanceHistory(
      FutureOr<Map<String, dynamic>> _response) async {
    final response = await _response;
    return PerformanceHistoryModel.fromJson(response);
  }

Upvotes: 1

Related Questions