Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

dart - JSON API with Flutter is not fetching data

I have a problem fetching data from a json api. I have this structure:

{
    "team": {
        "team_name": "Team Name",
        "team_quantity": 10,
        "team_victory": 2,
    }
}

and I'm trying to fetch data with Flutter:

class Team{
 final String name;
 final int quantity;
 final int victory;

  Team({this.name, this.quantity, this.victory});

  factory Team.fromJson(Map<String, dynamic> json){
    return Team(
      name: json['team_name'] as String,
      quantity: json['team_quantity'] as int,
      victory: json['team_victory'] as int,
    );
  }
}

Future<List<Team>> fetchTeam(http.Client client) async {
  final response =
      await http.get('url');
  return compute(parseTeam, response.body);
}

List<Team> parseTeam(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Team>((json) => Team.fromJson(json)).toList();
}

I get this error:

I/flutter (25834): Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
I/flutter (25834): Receiver: _LinkedHashMap len:1
I/flutter (25834): Tried calling: cast<Map<String, dynamic>>()
I/flutter (25834): Found: cast<RK, RV>() => Map<RK, RV>

Could you explain the error(s) to me? Thanks so much!

Maybe my problem could be the "team" in the api? I will try fetching data with the same structure in Flutter:

{
    "team": {
        "team_name": "Team Name",
        "team_quantity": 10,
        "team_victory": 2,
    }
}

or

{
   "team_name": "Team Name",
   "team_quantity": 10,
   "team_victory": 2,
}
question from:https://stackoverflow.com/questions/65641161/json-api-with-flutter-is-not-fetching-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try replacing

final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();

with

final Map<String, dynamic> parsed = jsonDecode(responseBody);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...