Home > Software design >  Not able to get users data from backend in flutter using http package
Not able to get users data from backend in flutter using http package

Time:10-22

I'm trying to fetch users data from the backend, my api works fine after several postman tests. The problem is that i'm always getting a null value whenever I try to show them in the flutter console.

Here is my model:

import 'dart:convert';

List<UserModel> userModelFromJson(String str) =>
    List<UserModel>.from(json.decode(str).map((x) => UserModel.fromJson(x)));

class UserModel {
  const UserModel({
    required this.id,
    required this.name,
    required this.password,
    required this.phone,
    required this.idRelation,
    required this.relation,
    required this.status,
    required this.photo,
    required this.age,
  });

  final int id;
  final String name;
  final String password;
  final int phone;
  final int idRelation;
  final String relation;
  final bool status;
  final String photo;
  final int age;

  factory UserModel.fromJson(Map<dynamic, dynamic> json) => UserModel(
        id: json["id"],
        name: json["name"],
        password: json["password"],
        phone: json["phone"],
        idRelation: json["idRelation"],
        relation: json["relation"],
        status: json["status"],
        photo: json["photo"],
        age: json["age"],
      );
}

my service:

class RemoteService {
  Map<String, String> headers = {
    'Content-Type': 'application/json;charset=UTF-8',
    'Charset': 'utf-8'
  };

  Future<List<UserModel>?> getUsers() async {
    final response = await http.get(Uri.parse("http://192.168.1.5:3000/user"),
        headers: headers);
    if (response.statusCode == 200) {
      var json = response.body;
      return userModelFromJson(json);
    }
  }
}

and the UI part:

List<UserModel>? users;

  @override
  void initState() {
    super.initState();
    getData();
  }

  getData() async {
    users = await RemoteService().getUsers();
    print('Test');
    print('========================= ');
    print(users);
  }

The users print returns a null value, but I think i've done it all perfectly I don't know why i'm getting a null value! I'd be glad if anyone can help!

CodePudding user response:

As you mentioned in comment, your json response is an Object having an Array of UserModel(s). I am assuming an Json Object as.

{
    "UserModel": [{
            "id": 0,
            "name": "Hello"
        },
        {
            "id": 0,
            "name": "Hello"
        }
    ]
}

Then your model class will be,

// To parse this JSON data, do
//
//     final userModelResponse = userModelResponseFromJson(jsonString);

import 'dart:convert';

UserModelResponse userModelResponseFromJson(String str) => UserModelResponse.fromJson(json.decode(str));

String userModelResponseToJson(UserModelResponse data) => json.encode(data.toJson());

class UserModelResponse {
    UserModelResponse({
        this.userModel,
    });

    List<UserModel> userModel;

    factory UserModelResponse.fromJson(Map<String, dynamic> json) => UserModelResponse(
        userModel: List<UserModel>.from(json["UserModel"].map((x) => UserModel.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "UserModel": List<dynamic>.from(userModel.map((x) => x.toJson())),
    };
}

class UserModel {
    UserModel({
        this.id,
        this.name,
    });

    int id;
    String name;

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

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

For Json parsing, I am using https://app.quicktype.io/ this tool/site.

CodePudding user response:

I would suggest you to parse your json here: https://javiercbk.github.io/json_to_dart/

Then you can add this dart file in your code and run it, I think its a parsing issue nothing else. This link just converts your json to dart accurately

  • Related