Home > Back-end >  Flutter why does (json.decode(str) as List<dynamic>).map((e) not work?
Flutter why does (json.decode(str) as List<dynamic>).map((e) not work?

Time:08-18

Passing data stops working in the model while id debug mode

https://i.stack.imgur.com/y9j9U.png

https://i.stack.imgur.com/xyOWA.png,

I am not even sure exactly what the problem is. It ain't a session error(it was a problem before).

The mistake is probably arround here:

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

And this is the data i'm passing

{"total":6,"data":[{"id":"mt_133daa03e5c983e6561666ccf","name":"Biokovo"},{"id":"mt_hghgaa03e5c983e6561666dd1","name":"Dinara"},{"id":"mt_62daa03e5c983e65616660f4","name":"Medvednica"},{"id":"mt_cc2gaa03e5c983e6561666tr4","name":"Papuk"},{"id":"mt_1adaa03e5c983e65616664d4","name":"Samoborsko gorje"},{"id":"mt_tt5daa03e5c983e6561666a37","name":"Sjeverni Velebit"}]}

This it the whole model

List<SearchMountainDtoModel> searchMountainFromJson(String str) =>
    (json.decode(str) as List<dynamic>).map((e) => SearchMountainDtoModel.fromJson(e)).toList();

String searchMountainToJson(List<SearchMountainDtoModel> data) =>
    json.encode(data.map((e) => e.toJson()).toList());

class SearchMountainDtoModel {
  SearchMountainDtoModel({
    required this.name,

  });

  String name;

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

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

  };
}

Only error that I can see: [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null. E/flutter ( 9810): Receiver: null maybe its not related to this

CodePudding user response:

Because json.decode(str) is not the list, json.decode(str)['data'] is.

  • Related