Parse json in background using Dart's 'compute'

Issue

I am trying to use Json using the ‘compute’ method as I investigate ways to speed up my application. https://api.flutter.dev/flutter/foundation/compute.html.

No mention of an install for a package and use cases that I see do not mention any particular imports. https://dev.to/fallenstedt/compute-with-flutter-3p6o, https://github.com/flutter/flutter/issues/16265, Flutter- compute method

Error message:

Compiler message:
lib/account_control.dart:34:26: Error: Method not found: 'compute'.
      parsedJson = await compute(jsonDecode, response.body);

Where I call compute

if (response.statusCode == 200) {
  parsedJson = await compute(jsonDecode, response.body);
  Globals.data = parsedJson;
  print("Succesfully set Globals.data");
  return true;
}

Class implementation


    class AccountControl {
      static dynamic getAccDetails() async {
        var token = Globals.token;

        Globals.tokenDecode = Globals.parseJwt(Globals.token);
        Globals.accountId = Globals.tokenDecode["accountId"].toString();
        Globals.appUserId = Globals.tokenDecode["appUserId"].toString();
        Globals.partitionId = 0;

        var baseUrl = Globals.baseUrl; //platform server
        var accountId = Globals.accountId;
        var host = Globals.host;
        var accDetailsUri =
            Uri.encodeFull(baseUrl + "t/rest/cp/v1.0/account/" + accountId);

        print(accDetailsUri);

        Map<String, String> headers = {
          'Accept': 'application/json',
          'Authorization': 'Bearer ' + token,
          'Cache-Control': 'no-cache',
          'Host': host
        };

        var response = await http.get(accDetailsUri, headers: headers);

        var parsedJson;

        if (response.statusCode == 200) {
          parsedJson = await compute(jsonDecode, response.body);
          Globals.data = parsedJson;
          print("Succesfully set Globals.data");
          return true;
        }
      }
    } 

Any feedback is appreciated

Solution

You need to import foundation.

import 'package:flutter/foundation.dart';

Answered By – Richard Heap

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *