Failed to load departments - flutter

Viewed 15

I am retrieving data from the API but I keep getting this error and I don't know why.

The throw Exception part of the message is what keeps printing

This is my apiservice class

class APIService {
 
  Apis _apis = Apis();
  Client client = http.Client();

  Future<List<Department>> getDepartments() async {
    http.Response response = await client.get(
      Uri.parse(_projectApis.streamsUrl),
    );

    if (response.statusCode == 200) {
      debugPrint("The response body is: ${response.body}");
      return (json.decode(response.body) as List)
          .map((data) => Department.fromJson(data))
          .toList();
    } else {
      throw Exception('Failed to load departments'); // This part of the message is 
               what keeps printing
     
    }
  }
}

This is my controller class

class DepartmentController extends GetxController {

RxList<Department> departmentList = <Department>[].obs;

  @override
  void onInit() {
    fetchDepartment();
    super.onInit();
  }

  void fetchDepartment() async {
    departmentList.value = await RemoteService().getDepartments();

    if (departmentList.isEmpty) {
      Get.snackbar(
        'Error',
        'No departments found',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    } else {
      Get.snackbar(
        'Success',
        'Departments loaded',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
    }
  }
}

This is my model class

import 'dart:convert';

Department departmentFromJson(String str) =>
    Department.fromJson(json.decode(str));

String departmentToJson(Department data) => json.encode(data.toJson());

class Department {
  Department({
    required this.name,
  });

  String name;

  factory Department.fromJson(Map<String, dynamic> json) => Department(
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "name": name,
      };
}
0 Answers
Related