Pass API Data to GetX Controller from class

Issue

How can I pass the decoded Data from my Api to my GetX Controller?

Here is my Class "Germany" and my fetchGermany() Function.

Future<Germany> fetchGermany() async {
  final response =
      await get(Uri.parse('https://api.corona-zahlen.org/germany'));

  if (response.statusCode == 200) {
    return Germany.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to get data');
  }
}

class Germany {
  int cases;
  int deaths;
  int recovered;
  double weekIncidence;
  double casesPer100k;
  int casesPerWeek;

  Germany(
      {required this.cases,
      required this.deaths,
      required this.recovered,
      required this.weekIncidence,
      required this.casesPer100k,
      required this.casesPerWeek});

  factory Germany.fromJson(Map<String, dynamic> json) {
    return Germany(
        cases: json["cases"],
        deaths: json["deaths"],
        recovered: json["recovered"],
        weekIncidence: json["weekIncidence"],
        casesPer100k: json["casesPer100k"],
        casesPerWeek: json["casesPerWeek"]);
  }
}

Here is my GetX controller which is empty at the moment:

class DetailController extends GetxController {

}

So basically I just want to be able to acceess this data:

    cases: json["cases"],
    deaths: json["deaths"],
    recovered: json["recovered"],
    weekIncidence: json["weekIncidence"],
    casesPer100k: json["casesPer100k"],
    casesPerWeek: json["casesPerWeek"]

Solution

While I agree with @DarShan that you don’t necessarily need a GetXController here, I still would just for the simple sake of using a stateless widget over a stateful widget. If for no other reason than less cluttered UI code and separating business logic.

Also not sure if your Api call function is global or if that’s just how you have it in your example, but if it is global I’d create a helper class.

class ApiHelper {
  Future<Germany> fetchGermany() async {
    final response =
        await get(Uri.parse('https://api.corona-zahlen.org/germany'));

    if (response.statusCode == 200) {
      return Germany.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to get data');
    }
  }
}

Then your GetX class can look like this.

class DetailController extends GetxController {
Germany germany;

  @override
  void onInit() async {
    super.onInit();
    final apiHelper = ApiHelper();
    germany = await apiHelper.fetchGermany();
  }
}

And here’s an example using GetView widget which is just a stateless widget with a built in controller of the type you provided without having to find it.

class GermanyExample extends GetView<DetailController> {
  @override
  Widget build(BuildContext context) {
    // access the initialized Germany object with controller.germany
    return // the rest of your UI
  }
}

Answered By – Loren.A

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.