Home > database >  Create a class that calls a future for reusability
Create a class that calls a future for reusability

Time:07-29

I have a future that is used a few different times on some pages and I'm trying to include it instead and reference it when needed to cut down on the code overhead.

I've created a working future and wrapped it inside a class, the problem is that Flutter states that

"2 positional argument(s) expected, but 0 found."

I've tried String and Function type declarations for the client variable and I am including them, but I'm not sure what else I'm missing here?

FetchCats.getCats(client: http.Client(), filter: filter);

class FetchCats {
  String client; <-- this shouldn't be string but I don't know what else to declare it as
  int catType;

  FetchCats({Key? key, required this.client, required this.catType});

  Future<List<CatDetails>> getCats(http.Client client, int catType) async {
 
    var ct = catType;
    var catResults;
 
    var response = await client.get(Uri.parse('/cats/breeds/$ct/'));
    if (response.statusCode == 200) {
      catResults = compute(convertCatDetails, response.body);
    } else {
       print("error");
    }
    return catResults;
  }
}

List<CatDetails> convertCatDetails(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
  return parsed
      .map<CatDetails>((json) => CatDetails.fromJson(json))
      .toList();
}

CodePudding user response:

Your function is defined using positional parameters, rather than named parameters, but you are calling it with named arguments.

Here are a few changes that should allow you to use the class as I think you're intending:

  1. It's not necessary to store catType on the class, since that's something you would probably change between requests - so it makes more sense to only pass it into the getCats function.

  2. To fix the positional parameter issue, you can also change catType into a named parameter.

  3. You don't need a Key parameter on the constructor - those are usually used with Widgets.

  4. The type of the client should be http.Client, not String.

With those changes, your class should look something like this:

class FetchCats {
  final http.Client client;

  FetchCats({required this.client});

  Future<List<CatDetails>> getCats({required int catType}) async {
    int ct = catType;
    var catResults;
 
    var response = await client.get(Uri.parse('/cats/breeds/$ct/'));
    if (response.statusCode == 200) {
      catResults = compute(convertCatDetails, response.body);
    } else {
       print("error");

       // Return an empty list, rather than the uninitialized catResults
       return []; 
    }
    return catResults;
  }
}
  • Related