错误未处理的异常:将对象转换为可编码对象失败:当我尝试将新数据添加到列表时出现“listActivities”实例

问题描述 投票:0回答:1

所以我尝试向活动添加一个新对象并将其存储在本地存储中,代码如下

 pushObjectWisata(selectedIndex, selectedObjectId) async {

    PengunjungModel dataObjectWisata = listObjectWisata
        .firstWhere((element) => element.id == selectedObjectId);


    listAktifitas[selectedIndex].dataAktifitas!.add(dataObjectWisata);

    await saveListAktifitas(listAktifitas);
  }

但是我收到了这个错误:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Converting object to an encodable object failed: Instance of 'listActivities'

listAktifitas 它本身是一个具有多级对象的列表。模型看起来像这样

class listActivities {
  String? namaAktifitas;
  int? statusAktifitas;
  int? countActivity;
  String? thumbnail;
  List<PengunjungModel>? dataAktifitas;

  listActivities({
    this.namaAktifitas,
    this.statusAktifitas,
    this.countActivity,
    this.thumbnail,
    this.dataAktifitas,
  });

  factory listActivities.fromJson(Map<String, dynamic> json) => listActivities(
        namaAktifitas: json['namaAktifitas'].toString(),
        countActivity: json['countActivity'],
        statusAktifitas: json['statusAktifitas'],
        thumbnail: json['thumbnail'].toString(),
        dataAktifitas: List<PengunjungModel>.generate(
          json['dataAktifitas'].length,
          (index) => PengunjungModel.fromJson(
              json['dataAktifitas'][index] ?? <String, dynamic>{}),
        ),
      );

  static List<listActivities> fromJsonList(dynamic jsonList) {
    final listAktifitas = <listActivities>[];
    if (jsonList == null) return listAktifitas;

    if (jsonList is List<dynamic>) {
      for (final json in jsonList) {
        listAktifitas.add(
          listActivities.fromJson(json),
        );
      }
    }

    return listAktifitas;
  }

  factory listActivities.fromRawJson(String str) =>
      listActivities.fromJson(jsonDecode(str));

  String toRawJson() => jsonEncode(toJson());

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['namaAktifitas'] = namaAktifitas;
    data['statusAktifitas'] = statusAktifitas;
    data['countActivity'] = countActivity;
    data['thumbnail'] = thumbnail;
    data['dataAktifitas'] = dataAktifitas;
    return data;
  }
}

如您所见,它与另一个列表有关系,即 pengungungModel List。模型看起来像这样:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:sbh_v2/model/pariwisata/foto.dart';
import 'package:sbh_v2/model/pariwisata/kategori_pengunjung.dart';

class PengunjungModel {
  String? title;
  int? id;
  String? harga_terendah;
  String? harga_tertinggi;
  String? deskripsi;
  String? jam_buka;
  String? jam_tutup;
  String? alamat;
  String? fasilitas;
  double? lat;
  double? lng;
  List<Foto>? list_foto = <Foto>[];
  KategoriPengunjung? kategoriPengunjung;

  PengunjungModel(
      {this.id,
      this.title,
      this.harga_terendah,
      this.harga_tertinggi,
      this.deskripsi,
      this.alamat,
      this.list_foto,
      this.jam_tutup,
      this.jam_buka,
      this.fasilitas,
      this.lat,
      this.lng,
      this.kategoriPengunjung});

  factory PengunjungModel.fromJson(Map<String, dynamic> json) =>
      PengunjungModel(
        id: json['id'],
        title: json['title'] ?? "-",
        alamat: json['alamat'] ?? "-",
        jam_buka: json['jam_buka'] ?? "-",
        jam_tutup: json['jam_tutup'] ?? "-",
        fasilitas: json['fasilitas'],
        lat: double.parse(json['lat'] ?? '0'),
        lng: double.parse(json['lng'] ?? '0'),
        harga_terendah: json['harga_terendah'] ?? "",
        harga_tertinggi: json['harga_tertinggi'] ?? "",
        deskripsi: json['deskripsi'] ?? "-",
        list_foto: List<Foto>.generate(
          json['foto'].length,
          (index) => Foto.formJson(
            json['foto'][index] ?? <String, dynamic>{},
          ),
        ),
        kategoriPengunjung: KategoriPengunjung.fromJson(
            json['kategori_layanan_pengunjung'] ?? <String, dynamic>{}),
      );

  factory PengunjungModel.fromRawJson(String str) =>
      PengunjungModel.fromJson(jsonDecode(str));
}

基本上我尝试将具有 spesic id 的 pengunjungModel 数据对象添加到具有特定索引的 listAktifitas...

在pushObjectWisata中,我尝试打印selectedIndex和selectedObjectId,它工作正常。但是当我尝试打印 dataObjectWisata 时,它返回该错误,并且当我将 dataObjectWisata 添加到 listAktivitas 时,也会发生同样的情况。

我不知道我不明白什么。但也许这是因为那两个的模型..

请帮助我......谢谢

flutter list dart object model
1个回答
0
投票

您在尝试对对象进行编码以进行存储时遇到错误,可能是在使用 JSON 编码时。当您尝试序列化没有相应 JSON 表示形式的对象时,通常会出现错误消息“将对象转换为可编码对象失败”。在代码片段中,您尝试保存

listAktifitas
,其中包含
listActivities
类型的对象,用于存储。要解决此错误,您需要确保
listAktifitas
内的所有对象都是可编码的。

要修复该错误,您需要确保

PengunjungModel
也有一个 toJson() 方法将其转换为可 JSON 编码的格式。以下是如何修改
toJson()
中的
listActivities
方法以正确编码
dataAktifitas

更新您的

listActivities
toJson()
方法,如下所示:

Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
  data['namaAktifitas'] = namaAktifitas;
  data['statusAktifitas'] = statusAktifitas;
  data['countActivity'] = countActivity;
  data['thumbnail'] = thumbnail;
  data['dataAktifitas'] = dataAktifitas != null
      ? dataAktifitas!.map((pengunjung) => pengunjung.toJson()).toList()
      : null; // Check if dataAktifitas is null to avoid runtime error
  return data;
}

确保

PengunjungModel
也实现了正确的
toJson()
方法。

Map<String, dynamic> toJson() {
 final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['title'] = this.title;
    data['harga_terendah'] = this.harga_terendah;
    data['harga_tertinggi'] = this.harga_tertinggi;
    data['deskripsi'] = this.deskripsi;
    data['jam_buka'] = this.jam_buka;
    data['jam_tutup'] = this.jam_tutup;
    data['alamat'] = this.alamat;
    data['fasilitas'] = this.fasilitas;
    data['lat'] = this.lat.toString();
    data['lng'] = this.lng.toString();
    if (this.list_foto != null) {
      data['foto'] = this.list_foto!.map((v) => v.toJson()).toList();
    }
    if (this.kategoriPengunjung != null) {
      data['kategori_layanan_pengunjung'] = this.kategoriPengunjung!.toJson();
    }
    return data;
  }

像这样修改

pushObjectWisata
函数:

Future<void> pushObjectWisata(int selectedIndex, String selectedObjectId) async{

  PengunjungModel? dataObjectWisata = listObjectWisata.firstWhereOrNull(
    (element) => element.id == selectedObjectId,
  );

  if (dataObjectWisata != null) {
    // Check if the dataAktifitas list is initialized
    if (listAktifitas[selectedIndex].dataAktifitas == null) {
      listAktifitas[selectedIndex].dataAktifitas = [];
    }

    // Add the dataObjectWisata to the dataAktifitas list
    listAktifitas[selectedIndex].dataAktifitas!.add(dataObjectWisata);

    // Convert listAktifitas to a JSON string
    String jsonListAktifitas = jsonEncode(
      listAktifitas.map((aktivitas) => aktivitas.toJson()).toList(),
    );

    // Save the JSON string to storage
    await saveListAktifitas(jsonListAktifitas);
  } else {
    print('PengunjungModel with id $selectedObjectId not found.');
  }
}

检查您的

listActivities
类的定义。确保其所有属性都是基本类型(如 String、int、double、bool)、列表或映射,或者如果它们是自定义类,则它们实现
toJson()
方法。

© www.soinside.com 2019 - 2024. All rights reserved.