1

I created my own service in .net core 5.0 version. I preferred flutter which is multi-platform for front end. However, although I tried many ways from the service I wrote, I could not get my data. I can pull data from free services such as jsonplaceholder. I have enabled CORS on the backend. The strings I use for the url are localhost:port, 127.0.0.1:port, 10.0.2.2:port, MyIpAddress:port didn't work. It returns socket exception as an error. Error = SocketException: Connection refused (OS Error:Connection refused, errno=111), address localhost, port:60074

class Department_Api {
  static Future<List<dynamic>> getData() async{
    // Future<List<Department>> _getDepartmentList();
    try {
      var request = http.Request('GET', Uri.parse('https://localhost:44318/api/departments'));
      http.StreamedResponse response = await request.send();
      List<Department> _departmentList = [];
      if (response.statusCode == 200) {
        final List<Department> rspns =await response.stream.bytesToString() as List<Department>;
        _departmentList =  rspns;
      }
      else {
        print(response.reasonPhrase);
      }
    } catch (e) {
      return Future.error(e.toString());
    }
    return [];
  }
  static Future<List<Department>> getAllDepartments() async {
    List temp = await getData(
    );
    return Department.departmentsToList(temp);
  }
}
class Department {
  late final int DepartmentId;
  late final String DepartmentName;
  late final int OrganizationId;

  Department(
      {required this.DepartmentId,
      required this.OrganizationId,
      required this.DepartmentName});

  factory Department.fromJson(Map<String, dynamic> json) {
    return Department(
        DepartmentId: json['DepartmentId'],
        OrganizationId: json['OrganizationId'],
        DepartmentName: json['DepartmentName']);
  }

    Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['deparmentId'] = DepartmentId;
    _data['departmentName'] = DepartmentName;
    _data['organizationID'] = OrganizationId;
    return _data;
  }

  static List<Department> departmentsToList(List departmentToList) {
    return departmentToList.map((data) {
      return Department.fromJson(data);
    }).toList();
  }
}
class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);
  static String routeName = "/home";
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Future<List<Department>>? myFuture;
  void initState() {
    myFuture = Department_Api.getAllDepartments();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Organizations",
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.white,
        centerTitle: true,
      ),
      body: Padding(
        padding: EdgeInsets.all(10.0),
        child: Column(
          children: <Widget>[
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: [
                  FutureBuilder<List<Department>>(
                    future: myFuture,
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        var myFutureList = snapshot.data!;
                        return ListView.builder(
                          itemCount: myFutureList.length,
                          itemBuilder: (context, index) {
                            var department = myFutureList[index];
                            return ListTile(
                              title: Text(department.DepartmentName),
                              subtitle: Text(department.DepartmentId.toString()),
                              leading: Text(department.OrganizationId.toString()),
                            );
                          },
                        );
                      } else if (snapshot.hasError) {
                        return Text(snapshot.error.toString());
                      } else
                      { return const CircularProgressIndicator();}
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Note: The department is a model class. Postman:enter image description here Http:enter image description here

Error:enter image description here

Goktug
  • 13
  • 5

1 Answers1

0

The problem is that you are not correctly parsing the response.

The value of response.stream.bytesToString() is a String and you are trying to cast it to List<Department> directly which causes the error message:

Excepted a value of type 'List<Department$>', but got one of type 'String'

To correctly parse the response you should be replacing:

final List<Department> rspns =await response.stream.bytesToString() as List<Department>;

with something like the following:

final responseBody = await response.stream.bytesToString();
final decodedResponse = jsonDecode(responseBody);
final List<Department> rspns = decodedResponse
      .map((department) => Department.fromJson(department))
      .toList<Department>();

NOTE: Do not forget to import dart:convert at the top of the file to access the method called jsonDecode():

import 'dart:convert';

Also fix the keys in fromJson() method inside the Department model to match the keys in the response like the following:

factory Department.fromJson(Map<String, dynamic> json) {
  return Department(
      DepartmentId: json['departmentId'],
      OrganizationId: json['organizationID'],
      DepartmentName: json['departmentName']);
}
Moaz El-sawaf
  • 2,306
  • 1
  • 16
  • 33
  • Thanks for replying but the error just changed. Expected a value of type 'int', but got one of type 'Null'. I have tried many type conversions but only the error is changing. I think there is another problem, but i have no idea – Goktug Aug 05 '22 at 12:44
  • That's because you are not implementing `fromJson()` method correctly, I have updated the answer, check it out. – Moaz El-sawaf Aug 05 '22 at 12:51
  • I made the change you said, I changed it from the main page, but the error changed again. Error: Expected a value of type 'List', but got one of type 'List' – Goktug Aug 05 '22 at 13:12
  • Try to print any value from the list after this line `_departmentList = rspns;` to see if we solved the first error or not. If you still face the same error, copy the snippet again from the answer, I have updated something. – Moaz El-sawaf Aug 05 '22 at 13:27