android 如何在Flutter中正确地将一个模型添加到另一个模型?

olhwl3o2  于 2023-05-27  发布在  Android
关注(0)|答案(1)|浏览(162)

我真的很困惑,我如何添加导演模型到我的节目模型。我正在用Flutter编写Android应用程序,它使用本地Django Rest API。
这是Django中的Director Model

class Director(models.Model):
    name = models.CharField(max_length=20)
    surname = models.CharField(max_length=20)
    country = models.CharField(max_length=20)
    image = models.ImageField(null=True, blank=True, upload_to="images/")

这是在Django中显示模型

class Show(models.Model):
    name = models.CharField(max_length=50)
    annotation = models.TextField(max_length=1000)
    language = models.CharField(max_length=20, null=True)
    image = models.ImageField(null=True, blank=True, upload_to="images/")
    director = models.ForeignKey(Director, on_delete=models.CASCADE, null=True)

这是Flutter中的Director Model

import 'package:flutter/widgets.dart';

class DirectorModel with ChangeNotifier {
  final int id;
  final String name;
  final String surname;
  final String image;

  DirectorModel({required this.id, required this.name, required this.surname, required this.image});

  factory DirectorModel.fromJson(dynamic json) {
    return DirectorModel(
      id: json['id'],
      name: json['name'] as String,
      surname: json['surname'] as String,
      image: json['image'] as String,
    );
  }

  static List<DirectorModel> directorFromSnapshot(List snapshot) {
    return snapshot.map((data) {
      return DirectorModel.fromJson(data);
    }).toList();
  }
}

这是在Flutter中显示模型

import 'package:flutter/widgets.dart';
import 'package:kulises_app/models/directors.dart';

class ShowsModel with ChangeNotifier {
  int id;
  String name;
  String annotation;
  String language;
  DirectorModel director;
  String image;

  ShowsModel(
      {required this.id,
      required this.name,
      required this.annotation,
      required this.language,
      required this.director,
      required this.image});

  factory ShowsModel.fromJson(dynamic json) {
    return ShowsModel(
      id: json['id'],
      director: DirectorModel.fromJson(json['director']),
      name: json['name'] as String,
      annotation: json['annotation'] as String,
      language: json['language'] as String,
      image: json['image'] as String,
    );
  }

  static List<ShowsModel> showsFromSnapshot(List snapshot) {
    print(snapshot);
    return snapshot.map((data) {
      return ShowsModel.fromJson(data);
    }).toList();
  }

}

我在这行director: DirectorModel.fromJson(json['director']),上得到这个错误_TypeError (type 'int' is not a subtype of type 'Map<String, dynamic>')。这么小的一个错误,我真的想不通……
这个想法是-我有这个信息页面上的一个节目,我需要显示导演的名字和姓氏。

mqxuamgl

mqxuamgl1#

发生的情况是,DirectorModel.fromJson(json['director'])给出了一个错误,因为它需要一个Map<String, dynamic>类型的参数,但得到的是int。这意味着json['director']返回一个int
调试步骤:
1.打印所有的JSON。
1.首先找出director条目的来源。
1.找出为什么它不是你期望的形式(int而不是Map<String,dynamic>)。
1.搞定
更新你的帖子,如果你遇到了问题或已经解决了问题。

相关问题