I have 2 things I want to compare and return a list of Strings for each of the matching Ids with the corresponding names. Example: I have a list of "genre_ids": [16, 878, 28] from a movie, and from another API I get a list of objects with id and name of the genres, { "id": 878, "name": "Science Fiction" }. Now I want to compare the list of genre_ids with the list of objects with ids and names and return a List of names with all the matching Ids. How do I do that? I tried using the .where() option but failed miserably.
JSON from genre list:
{
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 16,
"name": "Animation"
},
{
"id": 35,
"name": "Comedy"
},
{
"id": 10749,
"name": "Romance"
},
{
"id": 878,
"name": "Science Fiction"
},
]
}
JSON from movie list:
"results": [
{
"adult": false,
"genre_ids": [
16,
878,
28
],
"id": 610150,
"release_date": "2022-06-11",
"title": "Dragon Ball Super: Super Hero",
"vote_average": 7.5,
"vote_count": 126
},
]
Both models from the APIs:
class Movies {
int? id;
String? title;
String? overview;
List<dynamic>? genreIds;
dynamic voteAverage;
String? posterPath;
Movies({
this.id,
this.title,
this.overview,
this.genreIds,
this.voteAverage,
this.posterPath,
});
Movies.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
overview = json['overview'];
genreIds = json['genre_ids'].toList();
voteAverage = json['vote_average'];
posterPath = json['poster_path'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['id'] = id;
data['title'] = title;
data['overview'] = overview;
data['vote_average'] = voteAverage;
data['genre_ids'] = genreIds;
data['poster_path'] = posterPath;
return data;
}
}
class Genres {
int? id;
String? name;
Genres({
this.id,
this.name,
});
Genres.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'] as String;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['id'] = id;
data['name'] = name;
return data;
}
}
API calls:
Future<List<Movies?>> getAllMovies() async {
Response response = await Dio().get(Contants().moviesUrl);
return (response.data['results'] as List).map((movies) {
return Movies.fromJson(genres);
}).toList();
}
Future<List<Genres?>> getAllGenres() async {
Response response = await Dio().get(Contants().genresUrl);
return (response.data['genres'] as List).map((genres) {
return Genres.fromJson(genres);
}).toList();
}
Future builder:
FutureBuilder(
future: Future.wait([
RepositoryFromAPItoDB().gettAllMovies(),
RepositoryFromAPItoDB().getAllGenres()
]),
builder:
(BuildContext context, AsyncSnapshot<List<dynamic>?> snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data?[0].length,
itemBuilder: (BuildContext context, int index) {
return MoviesListTile(
title: snapshot.data?[0][index].title,
voteAverage: snapshot.data?[0][index].voteAverage,
description: snapshot.data?[0][index].overview,
posterPath: snapshot.data?[0][index].posterPath,
genreIds: snapshot.data?[0][index].genreIds,
genres: ['drama', 'somehting'],
);
},
);
}
},
),
Requested output of names from the list:
Widget getTextWidgets(List<String?> strings) {
return Row(
children: strings
.map((item) => Container(
child: Text(
item!,
),
),
),
)
.toList());
}
Any form of help is appreciated.
Is this what you wanted?
void main() {
Map<String, dynamic> genres = {
"genres": [
{"id": 28, "name": "Action"},
{"id": 12, "name": "Adventure"},
{"id": 16, "name": "Animation"},
{"id": 35, "name": "Comedy"},
{"id": 10749, "name": "Romance"},
{"id": 878, "name": "Science Fiction"},
]
};
Map<String, dynamic> movie = {
"adult": false,
"genre_ids": [16, 878, 28],
"id": 610150,
"release_date": "2022-06-11",
"title": "Dragon Ball Super: Super Hero",
"vote_average": 7.5,
"vote_count": 126
};
print(getGenres(movie, genres["genres"]));
}
List getGenres(Map movie, List genres) {
final Set movieGenreIds = Set.from(movie["genre_ids"]);
return genres
.where((g) => movieGenreIds.contains(g["id"]))
.map((g) => g["name"])
.toList();
}
The output:
[Action, Animation, Science Fiction]
Edit, using the models you provided.
List getGenres(Movie movie, List<Genre> genres) {
final Set movieGenreIds = Set.from(movie.genreIds);
return genres
.where((g) => movieGenreIds.contains(g.id))
.map((g) => g.name)
.toList();
}
Related
I've been trying to get a column from a array into a list, I'm can't seem to figure how to do it, and I couldn't find a solution online. Most of the array i find only aren't nested.
{
"status": true,
"data": {
"1": [
{
"id": "1",
"name": "500MB [SME]",
"price": "220",
"telco_price": "0"
},
{
"id": "2",
"name": "1GB [SME]",
"price": "410",
"telco_price": "0"
},
{
"id": "3",
"name": "2GB [SME]",
"price": "800",
"telco_price": "0"
},
],
"2": [
{
"id": "AIR1000",
"name": "1.5GB ",
"price": "920",
"telco_price": "920"
},
{
"id": "AIR2000",
"name": "4.5GB",
"price": "1840",
"telco_price": "1840"
},
{
"id": "AIR2500",
"name": "6GB",
"price": "2300",
"telco_price": "2300"
}
],
"3": [
{
"id": "9MOB500",
"name": "500MB",
"price": "400",
"telco_price": "400"
},
{
"id": "9MOB1000",
"name": "1.5GB",
"price": "850",
"telco_price": "850"
},
{
"id": "9MOB2000",
"name": "2GB",
"price": "1020",
"telco_price": "1020"
},
]
}
}
firstly, i want to get all names into a list variable which i can then populate easily on one of my page...
i want it into var nameList = []; where its' stated "1" then the next into another variable like that
Do on fetch like
import 'package:http/http.dart' as http;
....
List<DataClass> nameList = [];
fetch() async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
MyResponse myResponse = MyResponse.fromJson(data);
final values = myResponse.data?.values;
if (values != null) {
for (final v in values) {
if(v!=null) nameList.addAll(v.toList());
}
}
}
}
Try this model class
import 'dart:convert';
class MyResponse {
final bool? status;
final Map<String, List<DataClass>?>? data;
MyResponse({
this.status,
required this.data,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if(status != null){
result.addAll({'status': status});
}
if(data != null){
result.addAll({'data': data});
}
return result;
}
factory MyResponse.fromMap(Map<String, dynamic> map) {
return MyResponse(
status: map['status'],
data: Map<String, List<DataClass>?>.from(map['data']),
);
}
String toJson() => json.encode(toMap());
factory MyResponse.fromJson(String source) => MyResponse.fromMap(json.decode(source));
}
class DataClass {
final String? id;
final String? name;
final String? price;
final String? telco_price;
DataClass({
this.id,
this.name,
this.price,
this.telco_price,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if (id != null) {
result.addAll({'id': id});
}
if (name != null) {
result.addAll({'name': name});
}
if (price != null) {
result.addAll({'price': price});
}
if (telco_price != null) {
result.addAll({'telco_price': telco_price});
}
return result;
}
factory DataClass.fromMap(Map<String, dynamic> map) {
return DataClass(
id: map['id'],
name: map['name'],
price: map['price'],
telco_price: map['telco_price'],
);
}
String toJson() => json.encode(toMap());
factory DataClass.fromJson(String source) =>
DataClass.fromMap(json.decode(source));
}
I am trying to map a json list in my application using JSON Serializable. But I am not able to map it.
Following is the response from the API:
{
"code": 200,
"message": "Countries Lists",
"count": 250,
"data": [
{
"id": 1,
"name": "Afghanistan"
},
{
"id": 2,
"name": "Aland Islands"
},
{
"id": 3,
"name": "Albania"
},
{
"id": 4,
"name": "Algeria"
},
{
"id": 5,
"name": "American Samoa"
},
{
"id": 6,
"name": "Andorra"
},
{
"id": 7,
"name": "Angola"
},
{
"id": 8,
"name": "Anguilla"
},
{
"id": 9,
"name": "Antarctica"
},
{
"id": 10,
"name": "Antigua And Barbuda"
},
{
"id": 11,
"name": "Argentina"
},
{
"id": 12,
"name": "Armenia"
},
{
"id": 13,
"name": "Aruba"
},
{
"id": 14,
"name": "Australia"
},
{
"id": 15,
"name": "Austria"
},
{
"id": 16,
"name": "Azerbaijan"
},
{
"id": 17,
"name": "Bahamas The"
},
{
"id": 18,
"name": "Bahrain"
},
{
"id": 19,
"name": "Bangladesh"
},
{
"id": 20,
"name": "Barbados"
}
]
}
Following is my response file:
#JsonSerializable()
class BaseResponse {
#JsonKey(name: "code")
int? status;
#JsonKey(name: "message")
String? message;
}
#JsonSerializable(explicitToJson: true)
class AllCountryResponse extends BaseResponse {
#JsonKey(name: "data")
List<CountryResponse> data;
AllCountryResponse(this.data);
//from JSON
factory AllCountryResponse.fromJson(Map<String, dynamic> json) =>
_$AllCountryResponseFromJson(json);
//to JSON
Map<String, dynamic> toJson() => _$AllCountryResponseToJson(this);
}
#JsonSerializable()
class CountryResponse {
#JsonKey(name: "id")
String? id;
#JsonKey(name: "name")
String? name;
CountryResponse(this.id, this.name);
//from JSON
factory CountryResponse.fromJson(Map<String, dynamic> json) =>
_$CountryResponseFromJson(json);
//to JSON
Map<String, dynamic> toJson() => _$CountryResponseToJson(this);
}
I am able to generate the responses.g dart file.
Following is my mapper class file:
class Countries {
String id,name;
Countries(this.id,this.name);
}
class AllCountries{
List<Countries> countries;
AllCountries(this.countries);
}
extension CountryResponseMapper on CountryResponse? {
Countries toDomain() {
return Countries(
this?.id.orEmpty() ?? EMPTY, this?.name.orEmpty() ?? EMPTY);
}
}
extension AllCountriesResponseMapper on AllCountryResponse? {
AllCountries toDomain() {
return AllCountries(this?.data.map((e) => e.toDomain()).toList() ?? []);
}
}
Once I run my api I do get 200 status while using my bio, but after that it shows me the default error I have set, i.e. "Something went wrong". Which means there is an issue in mapping the response.
Can someone help me with mapping this list please?
This code should work.
This code is generated by a very small and simple script (which was written in a few minutes).
class Response {
Response(
{required this.code,
required this.message,
required this.count,
required this.data});
factory Response.fromJson(Map json) {
return Response(
code: json['code'] as int?,
message: json['message'] as String?,
count: json['count'] as int?,
data: json['data'] == null
? []
: (json['data'] as List).map((e) => Data.fromJson(e as Map)).toList(),
);
}
final int? code;
final String? message;
final int? count;
final List<Data> data;
static List<Response> fromJsonList(List json) {
return json.map((e) => Response.fromJson(e as Map)).toList();
}
Map<String, dynamic> toJson() {
return {
'code': code,
'message': message,
'count': count,
'data': data.map((e) => e.toJson()).toList(),
};
}
static List<Map<String, dynamic>> toJsonList(List<Response> list) {
return list.map((e) => e.toJson()).toList();
}
}
class Data {
Data({required this.id, required this.name});
factory Data.fromJson(Map json) {
return Data(
id: json['id'] == null ? 0 : json['id'] as int,
name: json['name'] == null ? '' : json['name'] as String,
);
}
final int id;
final String name;
static List<Data> fromJsonList(List json) {
return json.map((e) => Data.fromJson(e as Map)).toList();
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
};
}
static List<Map<String, dynamic>> toJsonList(List<Data> list) {
return list.map((e) => e.toJson()).toList();
}
}
Code generation script:
import 'dart:io';
import 'package:object_serializer/json_serializer_generator.dart';
import 'package:yaml/yaml.dart';
void main() {
final classes = loadYaml(_classes) as Map;
final g = JsonSerializerGenerator();
final classesCode = g.generateClasses(classes);
final values = {
'classes': classesCode,
};
var source = g.render(_template, values);
source = g.format(source);
File('bin/stackoverflow.dart').writeAsStringSync(source);
}
const _classes = r'''
Response:
fields:
code: int?
message: String?
count: int?
data: List<Data>
Data:
fields:
id: int
name: String
''';
const _template = r'''
{{classes}}
''';
hi stackers i have a problem with returning nested data in array object using flutter, the data has shown but i cant get what i want to get i have a response like this from my backend
"meta": {
"code": 200,
"status": "success",
"message": "Data list transaksi berhasil diambil"
},
"data": {
"current_page": 1,
"data": [
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1,
}
}
]
}
],
}
}
response above is from my backend that success fully return in my response print() in flutter but i want to get the nested data in items.menus its return error Class'_InternalLinkedHashMap<String, dynamic>'has no instance getter 'menus'
for better understanding my question ill provide full model, provider and my services
this is my service getOrderList() function that i call in the futureBuilder
var url = '$baseUrl/transaction';
var headers = {
'Content-type': 'application/json',
'Authorization': 'Bearer ${userModel.token}'
};
var response = await http.get(Uri.parse(url), headers: headers);
// print(response.body);
// print('berhasil get kategori');
if (response.statusCode == 200) {
List data = json.decode(response.body)['data']['data'];
List<TransactionModel> transaction = [];
for (var item in data) {
transaction.add(TransactionModel.fromJson(item));
}
// print(transaction);
return transaction;
} else {
throw Exception('Gagal get Categori');
}
}
and this is my model code
class TransactionModel {
int id;
int users_id;
String invoice;
int seat_number;
double total_price;
String payment_method;
String status;
List items;
// List menu;
TransactionModel({
this.id,
this.users_id,
this.invoice,
this.seat_number,
this.total_price,
this.payment_method,
this.status,
this.items,
// this.menu,
});
TransactionModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
users_id = json['users_id'];
invoice = json['invoice'];
seat_number = json['seat_number'];
total_price = double.parse(json['total_price'].toString());
payment_method = json['payment_method'];
status = json['status'];
items = json['items'];
// menu = json['items']['menus'];
}
Map<String, dynamic> toJson() {
return {
'id': id,
'users_id': users_id,
'invoice': invoice,
'seat_number': seat_number,
'items': items,
'total_price': total_price,
'payment_method': payment_method,
'status': status,
// 'menu': menu,
};
}
}
i already change the model data and try much method but its still not working, thats all on my code what should i do to call items.menus in result ?
It seems to be a problem within the model, you can use a json to dart to make model class from raw json. Keep the fetching logic as it is.
Json
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1
}
}
]
}
Model class
// To parse this JSON data, do
//
// final transactionModel = transactionModelFromMap(jsonString);
import 'dart:convert';
class TransactionModel {
TransactionModel({
this.id,
this.usersId,
this.invoice,
this.seatNumber,
this.totalPrice,
this.paymentMethod,
this.status,
this.items,
});
final int id;
final int usersId;
final String invoice;
final int seatNumber;
final int totalPrice;
final String paymentMethod;
final String status;
final List<Item> items;
factory TransactionModel.fromJson(String str) => TransactionModel.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory TransactionModel.fromMap(Map<String, dynamic> json) => TransactionModel(
id: json["id"],
usersId: json["users_id"],
invoice: json["invoice"],
seatNumber: json["seat_number"],
totalPrice: json["total_price"],
paymentMethod: json["payment_method"],
status: json["status"],
items: List<Item>.from(json["items"].map((x) => Item.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"id": id,
"users_id": usersId,
"invoice": invoice,
"seat_number": seatNumber,
"total_price": totalPrice,
"payment_method": paymentMethod,
"status": status,
"items": List<dynamic>.from(items.map((x) => x.toMap())),
};
}
class Item {
Item({
this.id,
this.menusId,
this.transactionsId,
this.quantity,
this.menus,
});
final int id;
final int menusId;
final int transactionsId;
final int quantity;
final Menus menus;
factory Item.fromJson(String str) => Item.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Item.fromMap(Map<String, dynamic> json) => Item(
id: json["id"],
menusId: json["menus_id"],
transactionsId: json["transactions_id"],
quantity: json["quantity"],
menus: Menus.fromMap(json["menus"]),
);
Map<String, dynamic> toMap() => {
"id": id,
"menus_id": menusId,
"transactions_id": transactionsId,
"quantity": quantity,
"menus": menus.toMap(),
};
}
class Menus {
Menus({
this.id,
this.name,
this.price,
this.description,
this.categoriesId,
});
final int id;
final String name;
final int price;
final String description;
final int categoriesId;
factory Menus.fromJson(String str) => Menus.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Menus.fromMap(Map<String, dynamic> json) => Menus(
id: json["id"],
name: json["name"],
price: json["price"],
description: json["description"],
categoriesId: json["categories_id"],
);
Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"price": price,
"description": description,
"categories_id": categoriesId,
};
}
I want to get data from API, my API data as DoctorModel inside it daysModel, inside daysModel is workTimeModel, each doctor has many days and has worktime.
I tried a lot of ways but still can't fix it.
note: I made my API from this website https://app.quicktype.io/
my code to get API data:
Response res = await get(
doctorsUrl ,
);
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
List<dynamic> data = body['data'];
List<DoctorInfoModel> doctors = data.map((dynamic item) => DoctorInfoModel.fromJson(item)).toList();
return doctors;
}
my API:
{
"id": 15,
"name": "Prof. Elton Quigley",
"about": "uHiKeKA1gq",
"stars": 5,
"location": "R59lmj1eud",
"latitude": 5,
"longitude": 5,
"notes": "yCl95VqUAz",
"days": [
{
"name": "سبت",
"pivot": {
"doctor_id": 15,
"day_id": 1,
"morning": "1",
"evening": "1"
}
},
{
"name": "أحد",
"pivot": {
"doctor_id": 15,
"day_id": 2,
"morning": "3",
"evening": "3"
}
},
{
"name": "إثنين",
"pivot": {
"doctor_id": 15,
"day_id": 3,
"morning": "5",
"evening": "5"
}
},
{
"name": "ثلاثاء",
"pivot": {
"doctor_id": 15,
"day_id": 4,
"morning": "4",
"evening": "4"
}
},
{
"name": "أربعاء",
"pivot": {
"doctor_id": 15,
"day_id": 5,
"morning": "5",
"evening": "5"
}
},
{
"name": "خميس",
"pivot": {
"doctor_id": 15,
"day_id": 6,
"morning": "4",
"evening": "4"
}
}
]
}
my DoctorModel:
// To parse this JSON data, do
//
// final doctorInfoModel = doctorInfoModelFromJson(jsonString);
import 'dart:convert';
DoctorInfoModel doctorInfoModelFromJson(String str) => DoctorInfoModel.fromJson(json.decode(str));
String doctorInfoModelToJson(DoctorInfoModel data) => json.encode(data.toJson());
class DoctorInfoModel {
DoctorInfoModel({
this.id,
this.name,
this.about,
this.stars,
this.location,
this.latitude,
this.longitude,
this.notes,
this.days,
});
int id;
String name;
String about;
int stars;
String location;
int latitude;
int longitude;
String notes;
List<Day> days;
factory DoctorInfoModel.fromJson(Map<String, dynamic> json) => DoctorInfoModel(
id: json["id"],
name: json["name"],
about: json["about"],
stars: json["stars"],
location: json["location"],
latitude: json["latitude"],
longitude: json["longitude"],
notes: json["notes"],
days: List<Day>.from(json["days"].map((x) => Day.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"about": about,
"stars": stars,
"location": location,
"latitude": latitude,
"longitude": longitude,
"notes": notes,
"days": List<dynamic>.from(days.map((x) => x.toJson())),
};
}
class Day {
Day({
this.name,
this.pivot,
});
String name;
Pivot pivot;
factory Day.fromJson(Map<String, dynamic> json) => Day(
name: json["name"],
pivot: Pivot.fromJson(json["pivot"]),
);
Map<String, dynamic> toJson() => {
"name": name,
"pivot": pivot.toJson(),
};
}
class Pivot {
Pivot({
this.doctorId,
this.dayId,
this.morning,
this.evening,
});
int doctorId;
int dayId;
String morning;
String evening;
factory Pivot.fromJson(Map<String, dynamic> json) => Pivot(
doctorId: json["doctor_id"],
dayId: json["day_id"],
morning: json["morning"],
evening: json["evening"],
);
Map<String, dynamic> toJson() => {
"doctor_id": doctorId,
"day_id": dayId,
"morning": morning,
"evening": evening,
};
}
How can I get data correctly?
I figured out how to get data.
I replaced these two lines:
List<dynamic> data = body['data'];
List<DoctorInfoModel> doctors = data.map((dynamic item) => DoctorInfoModel.fromJson(item)).toList();
by these:
var data = body['data'];
DoctorInfoModel doctorInfo = DoctorInfoModel.fromJson(data);
when my DoctorInfoModel is not a List, so I delete it.
Correct code to get API data:
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
var data = body['data'];
DoctorInfoModel doctorInfo = DoctorInfoModel.fromJson(data);
print(doctorInfo.name);
print(doctorInfo.about);
print(doctorInfo.days[0].name);
print(doctorInfo.days[0].pivot.morning);
return doctorInfo;
}
I am getting a response as key as numeric. How to map data for the following response
{
"1": [
{
"id": 6,
"name": "test 1"
},
{
"id": 8,
"name": "test 2"
},
{
"id": 7,
"name": "test 3"
}
],
"2": [
{
"id": 9,
"name": "ttt1"
},
{
"id": 5,
"name": "ttt3"
}
],
"3": [
{
"id": 4,
"name": "ttg",
"status_id": 1
}
]
}
Here is my model
import 'dart:convert';
Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));
String homeBannerModelToJson(Map<String, List<HomeBannerModel>> data) => json.encode(Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, List<dynamic>.from(v.map((x) => x.toJson())))));
class HomeBannerModel {
int id;
String name;
HomeBannerModel({this.id, this.name});
HomeBannerModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
name= json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
I need to take the value in UI as
var data1 = data['1'];
var data2= data['2'];
var data3= data['3'];
but I am getting errors. help how to get the data of each key in each of the variable
but while mapping I am getting errors I have added part of my code in UI
_message:"type 'Map<String, dynamic>' is not a subtype of type 'List'"
The following method will convert your json string to a valid map object so that you can get your data the way you wanted.
Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));
to access data
final data = homeBannerModelFromJson(your_json_string);
print(data['1'][0].name); // test 1
You current json structure is Map<String, List<Map<String, dynamic>>>
You can try something like
var json = {...};
json.forEach((key, list) {
list.forEach((homeBannerModelMap) {
HomeBannerModel hBM = HomeBannerModel.fromJson(homeBannerModelMap);
});
});
You getting the error because your data is the type of Map, not the List.
So you can do something like this:
// [data] is result banners
List data = [];
// [result] is your object variable {"1": [{"id": 1, "name": "Welcome!"}]} etc
// So .forEach method is used for iterating through your json object
result.forEach((k, v){
// in which iteration I will map every instance to List of [HomeBannerModel]
var value = v.map((banner) => HomeBannerModel.fromJson(banner)).toList();
//in result I will add the result to our [banners] List
data.add(value);
});
But in this case, you should do:
data1 = data[1] // use int as the key, result will be List of BannerModels [Instance of 'HomeBannerModel', Instance of 'HomeBannerModel']
instead of:
var data1 = data['1']; //use string as the key
Please try the following code with just one model 'HomeBannerModel'.
main() {
final Map<String, dynamic> json = {
"1": [
{"id": 6, "name": "test 1"},
{"id": 8, "name": "test 2"},
{"id": 7, "name": "test 3"}
],
"2": [
{"id": 9, "name": "ttt1"},
{"id": 5, "name": "ttt3"}
],
"3": [
{"id": 4, "name": "ttg", "status_id": 1}
]
};
final Map datas = {};
json.forEach((key, value) {
datas.addAll(
{"$key": value.map((ele) => HomeBannerModel.fromMap(ele)).toList()});
});
print(datas["1"]);
print(datas["2"]);
print(datas["3"]);
}
class HomeBannerModel {
final int id;
final String name;
final int status_id;
HomeBannerModel({
this.id,
this.name,
this.status_id,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'status_id': status_id,
};
}
factory HomeBannerModel.fromMap(map) {
if (map == null) return null;
return HomeBannerModel(
id: map['id'],
name: map['name'],
status_id: map['status_id'],
);
}
#override
String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}
You may also try with two models (1) Data and (2) HomeBannerModel. Please see the following code :
main() {
final Map<String, dynamic> json = {
"1": [
{"id": 6, "name": "test 1"},
{"id": 8, "name": "test 2"},
{"id": 7, "name": "test 3"}
],
"2": [
{"id": 9, "name": "ttt1"},
{"id": 5, "name": "ttt3"}
],
"3": [
{"id": 4, "name": "ttg", "status_id": 1}
]
};
final List<Data> data = [];
json.forEach((key, value) {
data.add(Data.fromMap({"id": key, "details": value}));
});
print(data.firstWhere((e) => e.dataID == '1').homeBannerModel);
print(data.firstWhere((e) => e.dataID == '2').homeBannerModel);
print(data.firstWhere((e) => e.dataID == '3').homeBannerModel);
}
class Data {
final String dataID;
final List<HomeBannerModel> homeBannerModel;
Data({
this.dataID,
this.homeBannerModel,
});
factory Data.fromMap(Map<String, dynamic> map) {
if (map == null) return null;
return Data(
dataID: map["id"],
homeBannerModel: (map["details"]
.map<HomeBannerModel>((ele) => HomeBannerModel.fromMap(ele))
.toList() as List<HomeBannerModel>));
}
#override
String toString() => 'Data(id: $dataID, details: $homeBannerModel)';
}
class HomeBannerModel {
final int id;
final String name;
final int status_id;
HomeBannerModel({
this.id,
this.name,
this.status_id,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'status_id': status_id,
};
}
factory HomeBannerModel.fromMap(map) {
if (map == null) return null;
return HomeBannerModel(
id: map['id'],
name: map['name'],
status_id: map['status_id'],
);
}
#override
String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}
From what I’m seeing in the sample response you shared , the kets are all string as should be... "1" is also String FYI.
Coming to the error you're getting its because you are probably using the var data1,data2,data3 as a map which it isn't.
var data1 = data['1'];
if you print this var you will get :
[
{
"id": 6,
"name": "test 1"
},
{
"id": 8,
"name": "test 2"
},
{
"id": 7,
"name": "test 3"
}
]
If you want to access the submap with id of 6 and name Test 1 do the following:
print(data1[0]);
to display name:
print(data1[0]["name"]);