Home > database >  flutter program: _CastError (type '_InternalLinkedHashMap<String, dynamic>' is not a
flutter program: _CastError (type '_InternalLinkedHashMap<String, dynamic>' is not a

Time:08-30

I want to display the json, but I got the error listed in the title. I have show the line that causing error. Can you help me fix it?

class _MainPage extends State<MainPage> {
  List<KomikModel>? listproduk;

  Future<List<KomikModel>> _fetchData() async {
    final jsondata =
        await rootBundle.rootBundle.loadString('assets/datakomik.json');

    final list = json.decode(jsondata) as List<dynamic>; // error in this line

    return list.map((e) => KomikModel.fromJson(e)).toList();
  }

Here is datakomik.json, I use nested json. This is my first time using json, so I don't know how to display the nested json.

{
  "data": [
    {
      "kategori": "New update",
      "data": [
        {
          "judul": "Jujutsu Kaisen",
          "image": "images/Jujutsu Kaisen_Volume 1.webp"
        },
        {
          "judul": "Vinland Saga",
          "image": "images/Vinland Saga_volume 01.jpg"
        },
        {
          "judul": "Hunter x Hunter",
          "image": "images/HxH_Volume 10.jpg"
        },
        {
          "judul": "One Piece",
          "image": "images/One Piece_Volume 1.webp"
        }
      ]
    },
    {
      "kategori": "Read",
      "data": [
        {
          "judul": "Kaguya-sama: Love is War",
          "image": "images/kaguya-sama_Volume 22.jpg"
        }
      ]
    }
  ]
}

CodePudding user response:

You are parsing your JSON as List, but usualy it is Map. Try to handle it similar like this:

final jsondata =
        await rootBundle.rootBundle.loadString('assets/datakomik.json');
final objects = json.decode(jsondata) as Map<String, dynamic>;

// And see that data you are recieving.

CodePudding user response:

You are receiving a map, and it contains data inside it, You can do

final list = jsonDecode(jsondata)["data"] as List<dynamic>; 

CodePudding user response:

As you can see in you json file, it contains Map not a list so try this:

final _data = json.decode(jsondata)["data"] as as List<dynamic>;
  • Related