Home > Mobile >  How can I get a user detail from Django API using flutter?
How can I get a user detail from Django API using flutter?

Time:07-24

I want to get the username of a user from another model from a django REST API but it's catching an exception in my flutter class model

_TypeError (type 'int' is not a subtype of type 'Map<String, dynamic>')

here's my flutter model

class Note {
  Note({
    this.id, required this.body, this.updated, this.created, required this.user,
  });

  int? id;
  String body;
  DateTime? updated;
  DateTime? created;
  User user;

  factory Note.fromJson(Map<String, dynamic> json) => Note(
        id: json["id"],
        body: json["body"] as String,
        updated: DateTime.parse(json["updated"]),
        created: DateTime.parse(json["created"]),
        user: User.fromJson(jsonDecode(json["user"]) ) == null ? null : json["user"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "body": body,
        "updated": updated?.toIso8601String(),
        "created": created?.toIso8601String(),
        "user": user == null ? null : user,
      };
}

class User {
  User({
    required this.id, required this.username, this.password, required this.email,
  });

  String id;
  String username;
  String? password;
  String email;

  factory User.fromJson(Map<String, dynamic> json) => User(
        id: json["id"],
        username: json["username"],
        password: json["password"],
        email: json["email"],
      );

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

below is a snipper of my design code from flutter where I want to display the

  _retrieveNotes() async {
    notes = [];
    List response = json.decode((await client.get(retrieveUrl)).body);
    response.forEach((element) {
      notes.add(Note.fromJson(element));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Notes'),
        ),
        body: ListView.builder(
          itemCount: _notes.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: Text(_notes[index].body),
              trailing: Text(_notes[index].user.username),
            );
          },
        ));
  }
}

code update:

below is my json file

[
    {
        "id": 1,
        "body": "debugging",
        "updated": "2022-07-24T03:39:57.188340Z",
        "created": "2022-07-24T03:39:57.188340Z",
        "user": "f1c84842-e146-4936-9659-e4872c012240"
    }
]

The exception occurring now is

Exception has occurred.
FormatException (FormatException: Unexpected character (at character 1)
f1c84842-e146-4936-9659-e4872c012240
^
)

here is my model from the database

class CustomUser(AbstractUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    email = models.EmailField(unique=True)

class Note(models.Model):
    user = models.ForeignKey(CustomUser, null=True, on_delete=models.CASCADE)
    body = models.TextField()
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.body[0:50]

    class Meta:
        ordering = ['-updated']

CodePudding user response:

User is String,

"user": "f1c84842-e146-4936-9659-e4872c012240"

so parsing is a simple assignment from the map.

String user;
user: json["user"] as String,

CodePudding user response:

I think it can't find the user because of this: "user": user == null ? null : user,

I think it should be better if you put the user

CodePudding user response:

  _retrieveNotes() async {
    notes = [];
    List response = json.decode((await client.get(retrieveUrl)).body);
    response.forEach((element) {
      notes.add(Note.fromJson(element));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Notes'),
        ),
        body: ListView.builder(
          itemCount: _notes.length,"3",
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: Text(_notes[index].body),
              trailing: Text(_notes[index].user.username),
            );
          },
        ));
  }
}

CodePudding user response:

The exception is because an int is getting returned from the API, and not a user type. In the API code, return a json object that matches the keys and value types Flutter expects. Similar to this:

response_data = {}
response_data['body'] = 'hello world'
response_data['user'] = {
'key': 'value'
}

The null check doesn't work because it isn't type null, it's type int.

  • Related