Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

dart - how to return json List using flutter

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

question from:https://stackoverflow.com/questions/65546506/how-to-return-json-list-using-flutter

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

1 Answer

0 votes
by (71.8m points)

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'];
  }
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...