0

i want to return json object list but i dont know how

i'm using the sample doc from flutter the here is my code

  Future<Album> fetchAlbum() async {
  final response =
  await http.get('https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}


class Album {
  final String userId;
  final List <String> Cm;
  Album({this.userId, this.Cm});

  factory Album.fromJson(Map<String, dynamic> json) {


      return Album(

      userId: json['Results'][0]['Make_Name'],
        Cm: for( var i = 0 ; i < json['Count']; i++ ) {
      Cm.add(json['Results'][i]['Make_Name']);
    }

    );
  }
}

the error in Cm: for... line

iKaka
  • 201
  • 1
  • 3
  • 8

3 Answers3

0

In your code snippet you did not created a class to refer Results list. Try bellow code snippet.

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<Album> fetchAlbum() async {
  final response = await http.get(
      'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json');

  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load album');
  }
}

class Album {
  int count;
  String message;
  String searchCriteria;
  List<Results> results;

  Album({this.count, this.message, this.searchCriteria, this.results});

  Album.fromJson(Map<String, dynamic> json) {
    count = json['Count'];
    message = json['Message'];
    searchCriteria = json['SearchCriteria'];
    if (json['Results'] != null) {
      results = new List<Results>();
      json['Results'].forEach((v) {
        results.add(new Results.fromJson(v));
      });
    }
  }
}

class Results {
  int makeID;
  String makeName;
  int modelID;
  String modelName;

  Results({this.makeID, this.makeName, this.modelID, this.modelName});

  Results.fromJson(Map<String, dynamic> json) {
    makeID = json['Make_ID'];
    makeName = json['Make_Name'];
    modelID = json['Model_ID'];
    modelName = json['Model_Name'];
  }
}

Saiful Islam
  • 1,151
  • 13
  • 22
0

As the for-loop is not returning the list to the cm field, you may try using .map to do the mapping and return it.

Cm: json['Results'].map((e)=>e['Make_Name']).toList()
CbL
  • 734
  • 5
  • 22
0

First off, Flutter is a Framework for Dart language, so you don't need Flutter to run that code. Run code below on console:

import 'dart:convert';

import 'package:http/http.dart' as http;

class NetService {
  static Future fetchJsonData(String url) {
    return
      http.get(url)
        .then((response) => response?.statusCode == 200 ? jsonDecode(response.body) : null)
        .catchError((err) => print(err));
  }

  static Future<void> fetchCarModels() {
    return 
      fetchJsonData('https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json')
        .then((response) {
          if (response != null) {
            final Map<String, dynamic> data = response;
            print('''
Count : ${data["Count"]}
Message : ${data["Message"]}
Search Criteria : ${data["SearchCriteria"]}
Models : 
${(data["Results"] as List)?.fold<String>("", (m, e) => m + (e as Map<String, dynamic>)["Model_Name"] + ", ")}
'''
            );
          }
        })
        .catchError((err) => print(err));
  }
}

void main(List<String> arguments) async {
  await NetService.fetchCarModels();
}